package net.huashitong.supervision.task.service;

import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.ZxingUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.supervision.excel.Entity.ExcelDataEntity;
import net.huashitong.supervision.excel.service.ExcelDataService;
import net.huashitong.supervision.task.dao.TaskMainDao;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.TaskBackNewFilter;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskSubFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.util.ExcelReaderUtil;
import net.huashitong.synthetical.newSupervision.util.HolidayUtils;
import net.huashitong.util.DateUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/8/6
 * Time: 17:57
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class TaskMainService extends StringPKService<TaskMain> {
    @Autowired
    private TaskMainDao taskMainDao;
    @Autowired
    @Lazy(true)
    private TaskSubService taskSubService;
    @Autowired
    @Lazy(true)
    private TaskUnitService taskUnitService;
    @Autowired
    @Lazy(true)
    private SysTableService tableService;
    @Autowired
    @Lazy(true)
    private SysDeptService sysDeptService;
    @Autowired
    @Lazy(true)
    private DeptService deptService;
    @Autowired
    @Lazy(true)
    private TaskLogEntityService taskLogEntityService;
    @Autowired
    @Lazy(true)
    private TaskCategoryService taskCategoryService;
    @Autowired
    @Lazy(true)
    private SysUserDao sysUserDao;
    @Autowired
    @Lazy(true)
    private CopeToService copeToService;
    @Autowired
    @Lazy(true)
    private TaskLogNewService taskLogNewService;
    @Autowired
    private SpecialTaskService specialTaskService;
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private TaskUserService taskUserService;

    @Autowired
    private SysLoginService sysLoginService;
    @Lazy
    @Autowired
    private TimeLimitService timeLimitService;
    @Autowired
    private SMSUtilService smsUtilService;
//    @Autowired
//    private SMSUtilService smsUtilService;//短信

    @Autowired
    private ExcelDataService excelDataService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TaskEndDateService endDateService;


    //设置主键
    @Override
    protected void beforeSave(TaskMain obj) {
        obj.setSysId(tableService.updateMaxSysId("t_task_main", null));
    }

    public void save(TaskMain obj, String userId) {
        Date date = new Date();
        String date1 = net.huashitong.supervision.task.util.HolidayUtils.sdf1.format(date);
        String time = net.huashitong.supervision.task.util.HolidayUtils.sdf2.format(date);
        obj.setSysId(tableService.updateMaxSysId("t_task_main", null));
        obj.setCreateUser(userId);
        obj.setUpdUser(userId);
        obj.setCreateDate(date1);
        obj.setCreateTime(time);
        obj.setUpdDate(date1);
        obj.setUpdTime(time);
        getDao().save(obj);
    }

    @Override
    protected BaseDao<TaskMain, String> getDao() {
        return taskMainDao;
    }

    SimpleDateFormat simdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat simdate1 = new SimpleDateFormat("yyyy-MM-dd");
    private static String[] parsePatterns = {"yyyy-MM-dd"};

    /**
     * 会议纪要时限格式转换
     *
     * @param time
     * @return
     */
    public String changeTime(String time) {
        try {
            Date date = new Date();
            int i = Integer.parseInt(time);
            //设置任务时限 将天数转换成日期
            List<String> holidays = new ArrayList<>();
            Date datetime = HolidayUtils.getScheduleActiveDate(date, holidays, i);
            String format = simdate1.format(datetime);
            return format;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 更新待立项任务
     *
     * @param filter
     * @return
     * @throws Exception
     */
    public String updateTask(TaskMainFilter filter) throws Exception {
        HashMap<String, HashMap<String, String>> smsMap = new HashMap<>();//发短信专用

        String userId = "";
        if (StringUtils.isNotBlank(filter.getUserId())) {
            userId = filter.getUserId();
        } else {
            userId = SysUserUtils.getUserId();
        }
        SysLogin login = sysLoginService.getById(userId);
        SysUser user = sysUserDao.getById(userId);
        TaskMain taskMain = taskMainDao.getById(filter.getSysId());
//        filter.getCrucialUser()
      //  taskMain.setImp(2);// taskMain表中  1 重大事项， 2  攻坚。    specialTable 中 1 攻坚，2 重大事项；
        String s1 = taskMain.getgJFile();
        String s2 = taskMain.getgJFileName();
        String crucialUser = taskMain.getCrucialUser();
        BeanUtils.copyProperties(filter, taskMain);
        //补充攻坚附件参数
        taskMain.setgJFile(s1);
        taskMain.setgJFileName(s2);
        taskMain.setCrucialUser(crucialUser);
        if (StringUtils.isNotBlank(filter.getOverdueDept())) {
            //设置督办单位为待办
            taskMain.setOverdueDeptState("0");
        }
        //设置督查立项单位id
        taskMain.setInspectionId(login.getDeptId());
        //如果审批id不为空，将状态设置为待审批(0待审批，1审批未通过，2正常(待签收)，3已反馈4已完成，，删除10）
        if (StringUtils.isNotBlank(filter.getAuditorId())) {
            taskMain.setStatus("0");
        } else {
            taskMain.setStatus("2");//（没有审核即直接立项成功，状态为正常待签收）
        }
        //待立项状态更改
        taskMain.setCreateUser(userId);
       /* if (taskMain.getCreateUser().equals(taskMain.getCrucialUser())){

        }*/
        //this.update(taskMain);
        //如果有抄送，添加抄送列表
        if (filter.getCopeToIds() == null || filter.getCopeToIds().size() <= 0) {
        } else {
            List<String> copeToIds = filter.getCopeToIds();
            for (String copeToId : copeToIds) {
                CopeTo copeTo = new CopeTo();
                copeTo.setLeaderId(copeToId);
                copeTo.setStatus("0");
                copeTo.setTaskMainId(taskMain.getSysId());
                copeToService.save(copeTo, user.getSysId());
            }
        }
        //每月
        int year = Calendar.getInstance().get(Calendar.YEAR);//年
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;//月
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);//日
        //取出子事项集合
        //先去缓存找子任务；
        List<TaskSubFilter> taskSubFilterList = null;
        String batchNum = redisService.get("batchNum:" + userId);
        if (StringUtils.isBlank(batchNum)) {

            taskSubFilterList = filter.getTaskSubFilterList();
        } else {

            //批次号
            List<ExcelDataEntity> byBatchNum = excelDataService.getByBatchNum(batchNum);
            List<ExcelDataEntity> collect = byBatchNum.stream().filter(entity -> entity.getFlags() == 0).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(collect)) {
                return "导入事项中存在校验不通过事项，请先确保数据的准确性在操作";
            }
            taskSubFilterList = excelDataService.ExceltoEntity(byBatchNum);
            if (taskSubFilterList == null || taskSubFilterList.size() == 0) {
                return "请添加牵头单位";
            }
        }
//        List<TaskSubFilter> taskSubFilterList = filter.getTaskSubFilterList();
        int i = 0;//记录单位任务数量
       /* if (taskSubFilterList == null || taskSubFilterList.size() <= 0) {
            if (filters != null && filters.size() > 0) {
                taskSubFilterList = filters;
            } else {
                throw new Exception("请添加单位");
            }
        }*/
        int a = 0;
        if (taskSubFilterList != null && taskSubFilterList.size() > 0) {
            for (TaskSubFilter taskSubFilter : taskSubFilterList) {
                if (StringUtils.isBlank(taskSubFilter.getLeadDeptIds())) {
                    continue;
                }
                a++;
                TaskSub taskSub = new TaskSub();
                taskSub.setStatus(taskMain.getStatus());//子任务状态与主任务相同
                taskSub.setTaskMainId(taskMain.getSysId());
                if (StringUtils.isBlank(taskSubFilter.getSubName())) {
                    //如果子事项名称为空，将主任务名称赋值到子任务名字
                    taskSub.setSubName(filter.getMainName());
                } else {
                    taskSub.setSubName(taskSubFilter.getSubName());
                }
                if (StringUtils.isBlank(taskSubFilter.getSubTimeLimit())) {
                    //如果子事项时限为空，将主任务时限赋值到子任务    修改子任务时限；
                    if ("1".equals(filter.getTimeType())) {
                        //时限
                        taskSub.setTimeType("1");
                        taskSub.setSubTimeLimit(filter.getTimeLimit());
                    } else if ("2".equals(filter.getTimeType())) {
                        taskSub.setTimeType("2");
                        taskSub.setPeriod(filter.getPeriod());
                        taskSub.setDay(filter.getDay());
                        taskSub.setWeek(filter.getWeek());
                        taskSub.setMonth(filter.getMonth());
                        taskSub.setQuarter(filter.getQuarter());
                    } else {
                        taskSub.setTimeType("3");
                        taskSub.setTimeLimits(filter.getTimeLimits());
                    }
                } else {
                    //单时限
                    taskSub.setTimeType("1");
                    taskSub.setSubTimeLimit(taskSubFilter.getSubTimeLimit());
                }
                taskSubService.save(taskSub, user.getSysId());
                TimeLimit timeLimit = new TimeLimit();
                timeLimit.setTaskSubId(taskSub.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(taskSub.getTimeType());
                timeLimit.setPeriod(taskSub.getPeriod());
                timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                timeLimit.setTimeLimits(taskSub.getTimeLimits());
                timeLimit.setDay(taskSub.getDay());
                timeLimit.setWeek(taskSub.getWeek());
                timeLimit.setMonth(taskSub.getMonth());
                timeLimit.setQuarter(taskSub.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit, user.getSysId());
                //判断子事项是否有抄送领导
                if (ObjectUtils.isNotBlank(taskSubFilter.getSubCopeToIds())) {
                    //如果不为空
                    String subCopeToIds = taskSubFilter.getSubCopeToIds();
                    //切割抄送领导字符串
                    String[] split = subCopeToIds.split(",");
                    for (String subCopeToId : split) {
                        CopeTo copeTo = new CopeTo();
                        copeTo.setLeaderId(subCopeToId);
                        copeTo.setTaskMainId(taskMain.getSysId());
                        copeTo.setSubMainId(taskSub.getSysId());
                        copeTo.setStatus("0");
                        copeToService.save(copeTo, user.getSysId());
                    }
                }

                //取出牵头单位集合
                String leadDeptIds = taskSubFilter.getLeadDeptIds();
                if (StringUtils.isBlank(leadDeptIds)) {
                    throw new Exception("请添加单位");
                } else {
                    String[] strings = leadDeptIds.split(",");
                    for (String leadDeptId : strings) {
                        SysDept dept = sysDeptService.getById(leadDeptId);

                        TaskUnit taskUnit = new TaskUnit();
                        taskUnit.setDeptId(leadDeptId);
                        taskUnit.setUnitType("1");//牵头单位
                        taskUnit.setTaskMainName(taskMain.getMainName());
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubName(taskSub.getSubName());
                        taskUnit.setCategoryId(taskMain.getCategoryId());
                        taskUnit.setStatus(taskSub.getStatus());

                        if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                            taskUnit.setTimeType("1");
                            taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                            taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                        } else if ("2".equals(taskSub.getTimeType())) {
                            //周期性
                            taskUnit.setTimeType("2");
                            taskUnit.setPeriod(taskSub.getPeriod());
                            taskUnit.setWeek(taskSub.getWeek());
                            taskUnit.setMonth(taskSub.getMonth());

                            //修改时限错误的bug
                            String remindDate = DateUtil.getRemindDate(taskSub.getPeriod(), taskSub.getDay(), taskSub.getWeek(),
                                    taskSub.getMonth(), taskSub.getQuarter());
                            taskMain.setTimeLimit(remindDate);
                            taskUnit.setTimeLimit(remindDate);


                        } else {
                            //多时限
                            taskUnit.setTimeType("3");
                            taskUnit.setTimeLimits(taskSub.getTimeLimits());
                            //取出当前多时限的的第一个时限
                            if (taskSub.getTimeLimits().contains(",")) {
                                String[] split = taskSub.getTimeLimits().split(",");
                                taskUnit.setTimeLimit(split[0]);
                                taskMain.setTimeLimit(split[0]);
                            } else {
                                //只选择了一个
                                taskUnit.setTimeLimit(taskSub.getTimeLimits());
                                taskMain.setTimeLimit(taskSub.getTimeLimits());
                            }
                        }


                       /* if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                            taskUnit.setTimeType("1");
                            taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                            taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                        } else if ("2".equals(taskSub.getTimeType())) {
                            //周期性
                            taskUnit.setTimeType("2");
                            taskUnit.setPeriod(taskSub.getPeriod());
                            taskUnit.setWeek(taskSub.getWeek());
                            taskUnit.setMonth(taskSub.getMonth());

                            //**  待立项的单位任务时限；
                            if ("0".equals(taskSub.getPeriod())) {
                                //如果是按天的周期性反馈。
                                int dayInt = Integer.parseInt(taskSub.getDay());
                                long millis = System.currentTimeMillis();//当前时间的毫秒值
                                long timeLimitIong = millis + dayInt * 3600 * 24 * 1000;
                                String timeLimitDay = simdate1.format(timeLimitIong);//当前任务时限
                                taskUnit.setTimeLimit(timeLimitDay);
                                taskMain.setTimeLimit(timeLimitDay);
                            } else if ("1".equals(taskSub.getPeriod())) {
                                //如果是每周获取当前日期是周几
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(new Date());
                                int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                                if (w <= 0) {
                                    w = 7;
                                }
                                //判断周期性与当前星期的大小
                                if (w < Integer.parseInt(taskSub.getWeek())) {
                                    //如果小于，时限为本周周几
                                    Map<String, String> weekDate = WeekDayUtil.getWeekDate();
                                    String[] dates = WeekDayUtil.getDates(weekDate.get("mondayDate"), weekDate.get("sundayDate"), taskSub.getWeek());
                                    taskUnit.setTimeLimit(dates[0]);
                                    taskMain.setTimeLimit(dates[0]);
                                } else {
                                    //如果相同或者大于。时限为下周周几
                                    Date now = new Date();
                                    Map<String, String> nextWeek = WeekDayUtil.getNextWeek(simdate1.format(now));
                                    String[] dates = WeekDayUtil.getDates(nextWeek.get("beginDateNext"), nextWeek.get("endDateNext"), taskSub.getWeek());
                                    taskUnit.setTimeLimit(dates[0]);
                                    taskMain.setTimeLimit(dates[0]);
                                }
                            } else if ("2".equals(taskSub.getPeriod())) {
                                String yearStr = year + "";
                                String monthStr = month + "";
                                String dayStr = day + "";
                                if (month < 10) {
                                    monthStr = 0 + monthStr;
                                }
                                if (day < 10) {
                                    dayStr = 0 + dayStr;
                                }
                                //判断当前日期与周期的日期大小
                                if (day < Integer.parseInt(taskSub.getMonth())) {
                                    //如果小于。时限为本月日期
                                    String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                    taskUnit.setTimeLimit(time);
                                    taskMain.setTimeLimit(time);
                                } else {
                                    //不小于就是下月日期
                                    if (month == 12) {
                                        year = year + 1;
                                        String time = year + "-01-" + taskSub.getMonth();
                                        taskUnit.setTimeLimit(time);
                                    } else {
                                        month = month + 1;
                                        if (month < 10) {
                                            monthStr = "0" + month;
                                        }
                                        String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                        taskUnit.setTimeLimit(time);
                                        taskMain.setTimeLimit(time);
                                    }
                                }
                            } else {
                                //每季度
                                //第一个反馈时限
                                taskUnit.setTimeLimit(taskSub.getQuarter());
                                taskMain.setTimeLimit(taskSub.getQuarter());
                            }
                        } else {
                            //多时限
                            taskUnit.setTimeType("3");
                            taskUnit.setTimeLimits(taskSub.getTimeLimits());
                            //取出当前多时限的的第一个时限
                            if (taskSub.getTimeLimits().contains(",")) {
                                String[] split = taskSub.getTimeLimits().split(",");
                                taskUnit.setTimeLimit(split[0]);
                                taskMain.setTimeLimit(split[0]);
                            } else {
                                //只选择了一个
                                taskUnit.setTimeLimit(taskSub.getTimeLimits());
                                taskMain.setTimeLimit(taskSub.getTimeLimits());
                            }
                        }*/

                        //** end  单位任务时限；----
                        taskUnit.setDeptName(dept.getDeptName());
                        //设置为待办
                        taskUnit.setState("0");
                        //第一轮
                        taskUnit.setTimeRound("1");
                        taskUnitService.save(taskUnit, user.getSysId());
                        //发送短信。查询当前单位的领导
                        SysUserFilter userFilter = new SysUserFilter();
                        userFilter.setRoleId("02");
                        userFilter.setDeptId(dept.getSysId());
                        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                        for (SysLogin sysLogin : loginList) {
                            SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                            String mobile = sysUser.getMobile();
                            if (StringUtils.isNotBlank(mobile)) {
//                                smsUtilService.taskNewSmsService(taskUnit, sysUser);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("userName", sysUser.getName());
                                map.put("tel", sysUser.getMobile());
                                map.put("taskName", taskUnit.getTaskMainName());
                                smsMap.put(sysLogin.getSysId(), map);
                            }
                        }
                        i++;
                        //记录任务流程
                        if (StringUtils.isNotBlank(filter.getAuditorId())) {
                            TaskLogNew taskLogNew = new TaskLogNew();
                            taskLogNew.setTaskUnitId(taskUnit.getSysId());
                            SysUser auditor = sysUserDao.getById(filter.getAuditorId());
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + auditor.getName() + "审批";
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, user.getSysId());
                        }
                        if (filter.getCopeToIds() != null && filter.getCopeToIds().size() > 0) {
                            List<String> copeToIds = filter.getCopeToIds();
                            String names = "";
                            for (String copeToId : copeToIds) {
                                SysUser copeTo = sysUserDao.getById(copeToId);
                                String name = copeTo.getName();
                                names = names + name + " ";
                            }
                            TaskLogNew taskLogNew = new TaskLogNew();
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",抄送领导：" + names;
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew);

                        }
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(taskUnit.getSysId());
                        String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + dept.getDeptName() + "牵头";
                        taskLogNew.setContent(s);
                        taskLogNewService.save(taskLogNew, user.getSysId());
                    }
                    this.update(taskMain);
                }
                //取出协办单位
                String assistDeptIds = taskSubFilter.getAssistDeptIds();
                if (StringUtils.isNotBlank(assistDeptIds)) {
                    String[] strings = assistDeptIds.split(",");
                    for (String assistDeptId : strings) {
                        SysDept dept = sysDeptService.getById(assistDeptId);

                        TaskUnit taskUnit = new TaskUnit();
                        taskUnit.setDeptId(assistDeptId);
                        taskUnit.setUnitType("2");//xieban单位
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubName(taskSub.getSubName());
                        taskUnit.setCategoryId(taskMain.getCategoryId());
                        taskUnit.setTaskMainName(taskMain.getMainName());
                        taskUnit.setDeptName(dept.getDeptName());
                        taskUnit.setStatus(taskSub.getStatus());

                        if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                            taskUnit.setTimeType("1");
                            taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                            taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                        } else if ("2".equals(taskSub.getTimeType())) {
                            //周期性
                            taskUnit.setTimeType("2");
                            taskUnit.setPeriod(taskSub.getPeriod());
                            taskUnit.setWeek(taskSub.getWeek());
                            taskUnit.setMonth(taskSub.getMonth());

                            //修改时限错误的bug
                            String remindDate = DateUtil.getRemindDate(taskSub.getPeriod(), taskSub.getDay(), taskSub.getWeek(),
                                    taskSub.getMonth(), taskSub.getQuarter());
                            taskMain.setTimeLimit(remindDate);
                            taskUnit.setTimeLimit(remindDate);


                        } else {
                            //多时限
                            taskUnit.setTimeType("3");
                            taskUnit.setTimeLimits(taskSub.getTimeLimits());
                            //取出当前多时限的的第一个时限
                            if (taskSub.getTimeLimits().contains(",")) {
                                String[] split = taskSub.getTimeLimits().split(",");
                                taskUnit.setTimeLimit(split[0]);
                                taskMain.setTimeLimit(split[0]);
                            } else {
                                //只选择了一个
                                taskUnit.setTimeLimit(taskSub.getTimeLimits());
                                taskMain.setTimeLimit(taskSub.getTimeLimits());
                            }
                        }
                       /* if ("1".equals(taskSub.getTimeType())) {
                            taskUnit.setTimeType("1");
                            //判断协办单位是否有单独时限
                            if (StringUtils.isNotBlank(filter.getLessDays())) {
                                String format = xiebanLimit(taskSub.getSubTimeLimit(), filter.getLessDays());
                                taskUnit.setTimeLimit(format);
                            } else {
                                taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                            }
                        } else if ("2".equals(taskSub.getTimeType())) {
                            //周期性
                            taskUnit.setTimeType("2");
                            taskUnit.setPeriod(taskSub.getPeriod());
                            taskUnit.setWeek(taskSub.getWeek());
                            taskUnit.setMonth(taskSub.getMonth());
                            if ("0".equals(taskSub.getPeriod())) {
                                //如果是按天的周期性反馈。
                                int dayInt = Integer.parseInt(taskSub.getDay());
                                long millis = System.currentTimeMillis();//当前时间的毫秒值
                                long timeLimitIong = millis + dayInt * 3600 * 24 * 1000;
                                String timeLimitDay = simdate1.format(timeLimitIong);//当前任务时限
                                taskUnit.setTimeLimit(timeLimitDay);
                                taskMain.setTimeLimit(timeLimitDay);
                            } else if ("1".equals(taskSub.getPeriod())) {
                                //如果是每周获取当前日期是周几
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(new Date());
                                int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                                if (w < 0) {
                                    w = 7;
                                }
                                //判断周期性与当前星期的大小
                                if (w < Integer.parseInt(taskSub.getWeek())) {
                                    //如果小于，时限为本周周几
                                    Map<String, String> weekDate = WeekDayUtil.getWeekDate();
                                    String[] dates = WeekDayUtil.getDates(weekDate.get("mondayDate"), weekDate.get("sundayDate"), taskSub.getWeek());
                                    //协办提前天
                                    if (StringUtils.isBlank(filter.getLessDays())) {
                                        taskUnit.setTimeLimit(dates[0]);
                                    } else {
                                        taskUnit.setTimeLimit(xiebanLimit(dates[0], filter.getLessDays()));
                                    }
                                } else {
                                    //如果相同。时限为下周周几
                                    Date now = new Date();
                                    Map<String, String> nextWeek = WeekDayUtil.getNextWeek(simdate1.format(now));
                                    String[] dates = WeekDayUtil.getDates(nextWeek.get("beginDateNext"), nextWeek.get("endDateNext"), taskSub.getWeek());
                                    //协办提前天
                                    if (StringUtils.isBlank(filter.getLessDays())) {
                                        taskUnit.setTimeLimit(dates[0]);
                                    } else {
                                        taskUnit.setTimeLimit(xiebanLimit(dates[0], filter.getLessDays()));
                                    }
                                }
                            } else if ("2".equals(taskSub.getPeriod())) {
                                String yearStr = year + "";
                                String monthStr = month + "";
                                String dayStr = day + "";
                                if (month < 10) {
                                    monthStr = 0 + monthStr;
                                }
                                if (day < 10) {
                                    dayStr = 0 + dayStr;
                                }
                                //判断当前日期与周期的日期大小
                                if (day < Integer.parseInt(taskSub.getMonth())) {
                                    //如果小于。时限为本月日期
                                    String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                    //协办提前天
                                    if (StringUtils.isBlank(filter.getLessDays())) {
                                        taskUnit.setTimeLimit(time);
                                    } else {
                                        taskUnit.setTimeLimit(xiebanLimit(time, filter.getLessDays()));
                                    }
                                } else {
                                    //不小于就是下月日期
                                    //不小于就是下月日期
                                    if (month == 12) {
                                        year = year + 1;
                                        String time = year + "-01-" + taskSub.getMonth();
                                        if (StringUtils.isBlank(filter.getLessDays())) {
                                            taskUnit.setTimeLimit(time);
                                        } else {
                                            taskUnit.setTimeLimit(xiebanLimit(time, filter.getLessDays()));
                                        }
                                    } else {
                                        month = month + 1;
                                        if (month < 10) {
                                            monthStr = "0" + month;
                                        }
                                        String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                        if (StringUtils.isBlank(filter.getLessDays())) {
                                            taskUnit.setTimeLimit(time);
                                        } else {
                                            taskUnit.setTimeLimit(xiebanLimit(time, filter.getLessDays()));
                                        }
                                    }
                                }
                            } else {
                                //季度
                                //每季度
                                //第一个反馈时限
                                taskUnit.setTimeLimit(xiebanLimit(taskSub.getQuarter(), filter.getLessDays()));
                            }
                        } else {
                            //多时限
                            taskUnit.setTimeType("3");
                            taskUnit.setTimeLimits(taskSub.getTimeLimits());
                            //取出当前多时限的的第一个时限
                            if (taskSub.getTimeLimits().contains(",")) {
                                String[] split = taskSub.getTimeLimits().split(",");
                                if (StringUtils.isBlank(filter.getLessDays())) {
                                    taskUnit.setTimeLimit(split[0]);
                                } else {
                                    taskUnit.setTimeLimit(xiebanLimit(split[0], filter.getLessDays()));
                                }
                            } else {
                                //只选择了一个
                                String format = xiebanLimit(taskSub.getSubTimeLimit(), filter.getLessDays());
                                taskUnit.setTimeLimit(format);
                            }
                        }*/
                        taskUnit.setDeptName(dept.getDeptName());
                        //设置为待办
                        taskUnit.setState("0");
                        //第一轮
                        taskUnit.setTimeRound("1");
                        taskUnitService.save(taskUnit, user.getSysId());
                       /* TimeLimit timeLimit = new TimeLimit();
                        timeLimit.setTaskUnitId(taskUnit.getSysId());
                        timeLimit.setTimeType(taskSub.getTimeType());
                        timeLimit.setPeriod(taskSub.getPeriod());
                        timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                        timeLimit.setTimeLimits(taskSub.getTimeLimits());
                        timeLimit.setState("1");
                        timeLimitService.save(timeLimit);*/
                        i++;
                        //发送短信。查询当前单位的领导
                        SysUserFilter userFilter = new SysUserFilter();
                        userFilter.setRoleId("02");
                        userFilter.setDeptId(dept.getSysId());
                        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                        for (SysLogin sysLogin : loginList) {
                            SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                            String mobile = sysUser.getMobile();
                            if (StringUtils.isNotBlank(mobile)) {
//                                smsUtilService.taskNewSmsService(taskUnit, sysUser);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("userName", sysUser.getName());
                                map.put("tel", sysUser.getMobile());
                                map.put("taskName", taskUnit.getTaskMainName());
                                smsMap.put(sysLogin.getSysId(), map);
                            }
                        }
                        //记录任务流程
                        if (StringUtils.isNotBlank(filter.getAuditorId())) {
                            TaskLogNew taskLogNew = new TaskLogNew();
                            taskLogNew.setTaskUnitId(taskUnit.getSysId());
                            SysUser auditor = sysUserDao.getById(filter.getAuditorId());
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + auditor.getName() + "审批";
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, user.getSysId());
                        }
                        if (filter.getCopeToIds() != null && filter.getCopeToIds().size() > 0) {
                            List<String> copeToIds = filter.getCopeToIds();
                            String names = "";
                            for (String copeToId : copeToIds) {
                                SysUser copeTo = sysUserDao.getById(copeToId);
                                String name = copeTo.getName();
                                names = names + name + " ";
                            }
                            TaskLogNew taskLogNew = new TaskLogNew();
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",抄送领导：" + names;
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, user.getSysId());

                        }
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(taskUnit.getSysId());
                        String s = user.getName() + "立项： " + taskSub.getSubName() + ",由" + dept.getDeptName() + "协办";
                        taskLogNew.setContent(s);
                        taskLogNewService.save(taskLogNew, user.getSysId());
                    }
                }
            }
            if (a <= 0) {
                throw new Exception("请添加单位");
            }
            //保存成功后将上次导入的清除
            taskMain.setTypeExplain("待签收: " + i + "; 待反馈: " + 0 + "; 已反馈: " + 0 + "; 重办: " + 0 + "; 完成: " + 0);
            taskMain.setOverdueExplain("逾期单位任务: " + 0);
            this.update(taskMain);
            //保存完后将上传此次上传的单位集合清空
            //发送短信

            for (Map.Entry<String, HashMap<String, String>> entry : smsMap.entrySet()) {
                HashMap<String, String> obj = entry.getValue();
                String taskName = obj.get("taskName");
                String tel = obj.get("tel");
                String userName = obj.get("userName");
                smsUtilService.taskNewSmsService(taskName, tel, userName);
            }
            filters.clear();
            return "保存成功";
        } else {
            throw new Exception("请添加单位");
        }
    }

    /**
     * 设置子任务
     *
     * @param filter
     * @return
     */
    private TaskSub setTaskSubDate(TaskSub taskSub, TaskMainFilter filter) {
        if ("1".equals(filter.getTimeType())) {
            //时限
            taskSub.setTimeType("1");
            taskSub.setSubTimeLimit(filter.getTimeLimit());
        } else if ("2".equals(filter.getTimeType())) {
            taskSub.setTimeType("2");
            taskSub.setPeriod(filter.getPeriod());
            taskSub.setDay(filter.getDay());
            taskSub.setWeek(filter.getWeek());
            taskSub.setMonth(filter.getMonth());
            taskSub.setQuarter(filter.getQuarter());
        } else {
            taskSub.setTimeType("3");
            taskSub.setTimeLimits(filter.getTimeLimits());
        }
        return taskSub;
    }


    private void setTaskSubTime(TaskSubFilter taskSubFilter, TaskSub taskSub, TaskMainFilter filter ) {

        switch (taskSubFilter.getTimeType()) {
            case "1":
                if (StringUtils.isNotBlank(taskSubFilter.getSubTimeLimit())) {
                    taskSub.setSubTimeLimit(taskSubFilter.getSubTimeLimit());
                    taskSub.setTimeType("1");

                } else {
                    setTaskSubDate(taskSub, filter);
                }
                break;
            case "2":

                if (StringUtils.isNotBlank(taskSubFilter.getPeriod())) {
                    taskSub.setTimeType("2");
                    taskSub.setSubTimeLimit(taskSubFilter.getSubTimeLimit());
                    switch (taskSubFilter.getPeriod()) {
                        case "0"://天
                            if (StringUtils.isNotBlank(taskSubFilter.getDay())) {
                                taskSub.setDay(taskSubFilter.getDay());
                                taskSub.setPeriod(0 + "");
                            }
                            break;
                        case "1":
                            if (StringUtils.isNotBlank(taskSubFilter.getWeek())) {
                                taskSub.setWeek(taskSubFilter.getWeek());
                                taskSub.setPeriod(1 + "");
                            }
                            break;
                        case "2":
                            if (StringUtils.isNotBlank(taskSubFilter.getMonth())) {
                                taskSub.setPeriod("2");
                                taskSub.setMonth(taskSubFilter.getMonth());
                            }
                            break;
                        case "3":
                            if (StringUtils.isNotBlank(taskSubFilter.getQuarter())) {
                                taskSub.setPeriod("3");
                                taskSub.setQuarter(taskSubFilter.getQuarter());
                            }
                            break;

                    }
                } else {
                    setTaskSubDate(taskSub, filter);
                }
                break;
            case "3":
                if (StringUtils.isNotBlank(taskSubFilter.getTimeLimits())) {
                    taskSub.setTimeType("3");
                    taskSub.setTimeLimits(taskSubFilter.getTimeLimits());
                } else {
                    setTaskSubDate(taskSub, filter);
                }
                break;
            default:
                setTaskSubDate(taskSub, filter);
                break;
        }
    }

    /**
     * 创建任务
     *
     * @param filter
     * @return
     * @throws Exception
     */
    public String createTask(TaskMainFilter filter) throws Exception {
        HashMap<String, HashMap<String, String>> smsMap = new HashMap<>();//发短信专用
        String mainTaskId = "";
        String userId = "";
        if (StringUtils.isNotBlank(filter.getUserId())) {
            userId = filter.getUserId();
        } else {
            userId = SysUserUtils.getUserId();
        }
        if (ObjectUtils.isBlank(userId)) {
            return "您已经超时，请刷新网页后，重新登录";
        }
        SysLogin login = sysLoginService.getById(userId);//获取当前登录用户
        //校验必填字段
        if (StringUtils.isBlank(filter.getMainName())) {
            return "请填写任务名";
        }
        if (StringUtils.isBlank(filter.getCategoryId())) {
            return "请选择事项类型";
        }
        //如果不是周期性任务，需填写任务时限
        if ("1".equals(filter.getTimeType())) {
            if (StringUtils.isBlank(filter.getTimeLimit())) {
                return "请填写任务时限";
            }
        } else if ("2".equals(filter.getTimeType())) {
            if ("0".equals(filter.getPeriod())) {
                //天的周期性任务
                if (StringUtils.isBlank(filter.getDay())) {
                    return "请填写任务时限";
                }
            } else if ("1".equals(filter.getPeriod())) {
                //周的周期性任务
                if (StringUtils.isBlank(filter.getWeek())) {
                    return "请填写任务时限";
                }
            } else if ("2".equals(filter.getPeriod())) {
                //月的周期性任务
                if (StringUtils.isBlank(filter.getMonth())) {
                    return "请填写任务时限";
                }
            } else {
                //季度的周期性任务
                if (StringUtils.isBlank(filter.getQuarter())) {
                    return "请填写任务时限";
                }
            }
        } else {
            if (StringUtils.isBlank(filter.getTimeLimits())) {
                return "请填写任务时限";
            }
        }
        // 单位重大立项的时限？？？
        if (!"".equals(filter.getOverdueDept()) && null != filter.getOverdueDept()) {
            if ("1".equals(filter.getTimeType2())) {
                if (StringUtils.isBlank(filter.getTimeLimit2())) {
                    return "请填写任务时限";
                }

            } else if ("2".equals(filter.getTimeType2())) {
                if ("0".equals(filter.getPeriod2())) {
                    //天的周期性任务
                    if (StringUtils.isBlank(filter.getDay2())) {
                        return "请填写任务时限";
                    }
                } else if ("1".equals(filter.getPeriod2())) {
                    //周的周期性任务
                    if (StringUtils.isBlank(filter.getWeek2())) {
                        return "请填写任务时限";
                    }
                } else if ("2".equals(filter.getPeriod2())) {
                    //月的周期性任务
                    if (StringUtils.isBlank(filter.getMonth2())) {
                        return "请填写任务时限";
                    }
                } else {
                    //季度的周期性任务
                    if (StringUtils.isBlank(filter.getQuarter2())) {
                        return "请填写任务时限";
                    }
                }
            } else {
            /*if (StringUtils.isBlank(filter.getTimeLimits2())) {
                return "请填写任务时限";
            }*/
            }
        }
        //如果不是周期性任务，需填写任务时限 单位重大


        //每月
        int year = Calendar.getInstance().get(Calendar.YEAR);//年
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;//月
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);//日
        SysUser user = sysUserDao.getById(userId);
        TaskMain taskMain = new TaskMain();
        if (!"20190807100000000002".equals(filter.getCategoryId())) {
            filter.setFileNumber(null);//不是会议纪要 文号 设置为空
        }
        if (!"20190919100000000001".equals(filter.getCategoryId())) {
            filter.setOverdueDept(null);
        }
        BeanUtils.copyProperties(filter, taskMain);
        //设置督查立项单位id
        taskMain.setInspectionId(login.getDeptId());
        //如果审批id不为空，将状态设置为待审批(0待审批，1审批未通过，2正常(待签收)，3已反馈4已完成，，删除10）
        if (StringUtils.isNotBlank(filter.getAuditorId())) {
            taskMain.setStatus("0");
        } else {
            taskMain.setStatus("2");//（没有审核即直接立项成功，状态为正常待签收）
        }
        this.save(taskMain, userId);

        TaskEndDate endEntity = new TaskEndDate();
        endEntity.setTaskMainId(taskMain.getSysId());
        endEntity.setEndDate(filter.getPlanEndDate());
        endDateService.save(endEntity);

        mainTaskId = taskMain.getSysId();
        //判断是否有 督办单位
        if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
            taskMain.setImp(1); // mainTask表 1=重大事项  2=攻坚事项； specialTask  1 = 攻坚  2=重大
            taskMain.setOverdueDeptState("0");// 0 默认代办  1 在办
            // 有督查责任单位,为单位重大事项
            SpecialTask specialTask = new SpecialTask();
            specialTask.setTaskMainId(taskMain.getSysId());
            specialTask.setTaskMainName(taskMain.getMainName());
            specialTask.setTaskType("2"); // 2=重大事项  1=攻坚事项
            specialTask.setType("0");//设置单位重大事项状态,0 未签收 1  待反馈
            specialTask.setStatus("1");//待办;
            specialTask.setTimeRound("1");
            specialTask.setCreateUser(userId);
            //设置特殊任务单独的任务反馈时限;
            specialTask.setTimeLimit(filter.getTimeLimit2());
            specialTask.setTimeType(filter.getTimeType2());
            specialTask.setPeriod(filter.getPeriod2());
            specialTask.setDay(filter.getDay2());
            specialTask.setWeek(filter.getWeek2());
            specialTask.setMonth(filter.getMonth2());
            specialTask.setQuarter(filter.getQuarter2());
            specialTask.setTimeLimits(filter.getTimeLimits2());
            specialTask.setOverdueDeptId(taskMain.getOverdueDept());

            //设置当轮次时限
            if ("1".equals(specialTask.getTimeType())) {
//                            单时限
                specialTask.setRoundLimit(specialTask.getTimeLimit());
                specialTaskService.save(specialTask, userId);
                TimeLimit timeLimit = new TimeLimit();

                //将时限内容存入时限表,做生成多轮任务准备
                timeLimit.setSpecialTaskId(specialTask.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(specialTask.getTimeType());
                timeLimit.setPeriod(specialTask.getPeriod());
                timeLimit.setTimeLimit(specialTask.getTimeLimit());
                timeLimit.setTimeLimits(specialTask.getTimeLimits());
                timeLimit.setDay(specialTask.getDay());
                timeLimit.setWeek(specialTask.getWeek());
                timeLimit.setMonth(specialTask.getMonth());
                timeLimit.setQuarter(specialTask.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit, userId);
            } else if ("2".equals(specialTask.getTimeType())) {
                //周期性

                String remindDate = DateUtil.getRemindDate(specialTask.getPeriod(), specialTask.getDay(),
                        specialTask.getWeek(), specialTask.getMonth(), specialTask.getQuarter());
                specialTask.setRoundLimit(remindDate);
                specialTaskService.save(specialTask, userId);
                TimeLimit timeLimit = new TimeLimit();

                //将时限内容存入时限表,做生成多轮任务准备
                timeLimit.setSpecialTaskId(specialTask.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(specialTask.getTimeType());
                timeLimit.setPeriod(specialTask.getPeriod());
                timeLimit.setTimeLimit(specialTask.getTimeLimit());
                timeLimit.setTimeLimits(specialTask.getTimeLimits());
                timeLimit.setDay(specialTask.getDay());
                timeLimit.setWeek(specialTask.getWeek());
                timeLimit.setMonth(specialTask.getMonth());
                timeLimit.setQuarter(specialTask.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit, userId);
            } else {
                //多时限 直接生成多条任务；

                String[] dates = specialTask.getTimeLimits().split(",");

                specialTask.setRoundLimit(dates[0]);
                // listTask.add(specialTask2);
                specialTaskService.save(specialTask, userId);
                TimeLimit timeLimit = new TimeLimit();
                timeLimit.setSpecialTaskId(specialTask.getSysId());
//                  timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(specialTask.getTimeType());
                timeLimit.setPeriod(specialTask.getPeriod());
                timeLimit.setTimeLimits(specialTask.getTimeLimits());
                timeLimit.setDay(specialTask.getDay());
                timeLimit.setWeek(specialTask.getWeek());
                timeLimit.setMonth(specialTask.getMonth());
                timeLimit.setQuarter(specialTask.getQuarter());
                timeLimit.setState("1");
                timeLimit.setTimeLimit(dates[0]);
                timeLimitService.save(timeLimit, userId);


            }

        }

        //如果有抄送，添加抄送列表
        if (filter.getCopeToIds() == null || filter.getCopeToIds().size() <= 0) {
        } else {
            List<String> copeToIds = filter.getCopeToIds();
            for (String copeToId : copeToIds) {
                if (StringUtils.isBlank(copeToId)) {
                    continue;
                }
                CopeTo copeTo = new CopeTo();
                copeTo.setLeaderId(copeToId);
                copeTo.setStatus("0");
                copeTo.setTaskMainId(taskMain.getSysId());
                copeToService.save(copeTo, userId);

            }
        }
        //取出子事项集合  批次号不为空，说明有导入，直接取导入的数据
        List<TaskSubFilter> taskSubFilterList = null;
        String batchNum = redisService.get("batchNum:" + userId);
        int i = 0;//记录单位任务数量
        if (StringUtils.isBlank(batchNum)) {

            taskSubFilterList = filter.getTaskSubFilterList();
        } else {

            //批次号
            List<ExcelDataEntity> byBatchNum = excelDataService.getByBatchNum(batchNum);
            List<ExcelDataEntity> collect = byBatchNum.stream().filter(entity -> entity.getFlags() == 0).collect(Collectors.toList());
            if (ObjectUtils.isNotBlank(collect)) {
                return "导入事项中存在校验不通过事项，请先确保数据的准确性在操作";
            }
            taskSubFilterList = excelDataService.ExceltoEntity(byBatchNum);
            if (taskSubFilterList == null || taskSubFilterList.size() == 0) {
                return "请添加牵头单位";
            }
        }
        int a = 0;
        if (taskSubFilterList != null && taskSubFilterList.size() > 0) {
            for (TaskSubFilter taskSubFilter : taskSubFilterList) {
                if (StringUtils.isBlank(taskSubFilter.getLeadDeptIds())) {
                    continue;
                }


                a++;
                TaskSub taskSub = new TaskSub();
                taskSub.setStatus(taskMain.getStatus());//子任务状态与主任务相同
                taskSub.setTaskMainId(taskMain.getSysId());
                if (StringUtils.isBlank(taskSubFilter.getSubName())) {
                    //如果子事项名称为空，将主任务名称赋值到子任务名字
                    taskSub.setSubName(filter.getMainName());
                } else {
                    taskSub.setSubName(taskSubFilter.getSubName());
                }
                //设置子任务时限
                setTaskSubTime(taskSubFilter, taskSub, filter);

                if (taskMain.getImp() == 1) {
                    taskSub.setImp(1);
                }
                //子任务表
                taskSubService.save(taskSub, userId);

                TimeLimit timeLimit = new TimeLimit();
                timeLimit.setTaskSubId(taskSub.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(taskSub.getTimeType());
                timeLimit.setPeriod(taskSub.getPeriod());
                timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                timeLimit.setTimeLimits(taskSub.getTimeLimits());
                timeLimit.setDay(taskSub.getDay());
                timeLimit.setWeek(taskSub.getWeek());
                timeLimit.setMonth(taskSub.getMonth());
                timeLimit.setQuarter(taskSub.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit, userId);

                //判断子事项是否有抄送领导
                if (ObjectUtils.isNotBlank(taskSubFilter.getSubCopeToIds())) {
                    //如果不为空
                    String subCopeToIds = taskSubFilter.getSubCopeToIds();
                    //切割抄送领导字符串
                    String[] split = subCopeToIds.split(",");
                    for (String subCopeToId : split) {
                        CopeTo copeTo = new CopeTo();
                        copeTo.setLeaderId(subCopeToId);
                        copeTo.setTaskMainId(taskMain.getSysId());
                        copeTo.setSubMainId(taskSub.getSysId());
                        copeTo.setStatus("0");
                        copeToService.save(copeTo, userId);

                    }
                }

                //取出牵头单位集合
                String leadDeptIds = taskSubFilter.getLeadDeptIds();
                if (StringUtils.isBlank(leadDeptIds)) {
                    return "请添加单位";
                } else {
                    String[] strings = leadDeptIds.split(",");
                    for (String leadDeptId : strings) {
                        SysDept dept = sysDeptService.getById(leadDeptId);
                        TaskUnit taskUnit = new TaskUnit();
                        taskUnit.setDeptId(leadDeptId);
                        taskUnit.setUnitType("1");//牵头单位
                        taskUnit.setTaskMainName(taskMain.getMainName());
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubName(taskSub.getSubName());
                        taskUnit.setCategoryId(taskMain.getCategoryId());
                        taskUnit.setStatus(taskSub.getStatus());

                        setTaskUnitTime(taskUnit,taskSub);
                        taskMain.setTimeLimit(taskUnit.getTimeLimit());

                        taskUnit.setDeptName(dept.getDeptName());
                        //设置为待办
                        taskUnit.setState("0");
                        //第一轮
                        taskUnit.setTimeRound("1");
                        if (taskMain.getImp() == 1) {
                            taskUnit.setImp(1);
                        }
                        taskUnitService.save(taskUnit, userId);
                        //设置单位任务时限；

                        //发送短信。查询当前单位的领导
                        SysUserFilter userFilter = new SysUserFilter();
                        userFilter.setRoleId("02");//公共账号
                        userFilter.setDeptId(dept.getSysId());
                        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                        for (SysLogin sysLogin : loginList) {

                            SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                            String mobile = sysUser.getMobile();
                            if (StringUtils.isNotBlank(mobile)) {
                                // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("userName", sysUser.getName());
                                map.put("tel", sysUser.getMobile());
                                map.put("taskName", taskUnit.getTaskMainName());
                                smsMap.put(sysLogin.getSysId(), map);
                            }


                        }
                        i++;
                        //记录任务流程
                        if (StringUtils.isNotBlank(filter.getAuditorId())) {
                            TaskLogNew taskLogNew = new TaskLogNew();
                            taskLogNew.setTaskUnitId(taskUnit.getSysId());
                            SysUser auditor = sysUserDao.getById(filter.getAuditorId());
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + auditor.getName() + "审批";
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, userId);

                        }
                        if (ObjectUtils.isNotBlank(filter.getCopeToIds())) {
                            List<String> copeToIds = filter.getCopeToIds();
                            String names = "";
                            for (String copeToId : copeToIds) {
                                if (StringUtils.isNotBlank(copeToId)) {
                                    String[] splitIds = copeToId.split(",");
                                    for (String s : splitIds) {
                                        SysUser copeTo = sysUserDao.getById(s);
                                        String name = copeTo.getName();
                                        names = names + name + " ";
                                    }
                                }

                            }
                            TaskLogNew taskLogNew = new TaskLogNew();
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",抄送领导：" + names;
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, userId);


                        }
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(taskUnit.getSysId());
                        String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + dept.getDeptName() + "牵头";
                        taskLogNew.setContent(s);
                        System.out.println("-------------------");
                        System.out.println(taskLogNew.getContent());
                        taskLogNewService.save(taskLogNew, userId);

                    }
                    this.update(taskMain);
                }
                //取出协办单位
                String assistDeptIds = taskSubFilter.getAssistDeptIds();
                if (StringUtils.isNotBlank(assistDeptIds)) {
                    String[] strings = assistDeptIds.split(",");
                    for (String assistDeptId : strings) {
                        SysDept dept = sysDeptService.getById(assistDeptId);

                        TaskUnit taskUnit = new TaskUnit();
                        taskUnit.setDeptId(assistDeptId);
                        taskUnit.setUnitType("2");//xieban单位
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubName(taskSub.getSubName());
                        taskUnit.setCategoryId(taskMain.getCategoryId());
                        taskUnit.setTaskMainName(taskMain.getMainName());
                        taskUnit.setDeptName(dept.getDeptName());
                        taskUnit.setStatus(taskSub.getStatus());

                        setTaskUnitTime(taskUnit,taskSub);
                        taskMain.setTimeLimit(taskUnit.getTimeLimit());

                        taskUnit.setDeptName(dept.getDeptName());
                        //设置为待办
                        taskUnit.setState("0");
                        //第一轮
                        taskUnit.setTimeRound("1");
                        taskUnit.setCreateUser(userId);
                        if (taskMain.getImp() == 1) {
                            taskUnit.setImp(1);
                        }
                        taskUnitService.save(taskUnit, userId);

                       /* TimeLimit timeLimit = new TimeLimit();
                        timeLimit.setTaskUnitId(taskUnit.getSysId());
                        timeLimit.setTimeType(taskSub.getTimeType());
                        timeLimit.setPeriod(taskSub.getPeriod());
                        timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                        timeLimit.setTimeLimits(taskSub.getTimeLimits());
                        timeLimit.setState("1");
                        timeLimitService.save(timeLimit);*/
                        //发送短信。查询当前单位的领导
                        SysUserFilter userFilter = new SysUserFilter();
                        userFilter.setRoleId("02");
                        userFilter.setDeptId(dept.getSysId());
                        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                        for (SysLogin sysLogin : loginList) {
                            SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                            String mobile = sysUser.getMobile();
                            if (StringUtils.isNotBlank(mobile)) {
                                // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("userName", sysUser.getName());
                                map.put("tel", sysUser.getMobile());
                                map.put("taskName", taskUnit.getTaskMainName());
                                smsMap.put(sysLogin.getSysId(), map);
                            }
                        }
                        i++;
                        //记录任务流程
                        if (StringUtils.isNotBlank(filter.getAuditorId())) {
                            TaskLogNew taskLogNew = new TaskLogNew();
                            taskLogNew.setTaskUnitId(taskUnit.getSysId());
                            SysUser auditor = sysUserDao.getById(filter.getAuditorId());
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + auditor.getName() + "审批";
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, userId);

                        }
                        if (filter.getCopeToIds() != null && filter.getCopeToIds().size() > 0) {
                            List<String> copeToIds = filter.getCopeToIds();
                            String names = "";
                            for (String copeToId : copeToIds) {
                                if (StringUtils.isNotBlank(copeToId)) {
                                    String[] splitIds1 = copeToId.split(",");
                                    for (String s : splitIds1) {
                                        SysUser copeTo = sysUserDao.getById(s);
                                        String name = copeTo.getName();
                                        names = names + name + " ";
                                    }
                                }
                            }
                            TaskLogNew taskLogNew = new TaskLogNew();
                            String s = user.getName() + "立项：" + taskSub.getSubName() + ",抄送领导：" + names;
                            taskLogNew.setContent(s);
                            taskLogNewService.save(taskLogNew, userId);


                        }
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(taskUnit.getSysId());
                        String s = user.getName() + "立项： " + taskSub.getSubName() + ",由" + dept.getDeptName() + "协办";
                        taskLogNew.setContent(s);
                        taskLogNewService.save(taskLogNew, userId);

                    }
                }
            }
            if (a <= 0) {
                throw new Exception("请添加单位");
            }
            //保存成功后将上次导入的清除
            taskMain.setTypeExplain("待签收: " + i + "; 待反馈: " + 0 + "; 已反馈: " + 0 + "; 重办: " + 0 + "; 完成: " + 0);
            taskMain.setOverdueExplain("逾期单位任务: " + 0);
            this.update(taskMain);
            //发送短信

            for (Map.Entry<String, HashMap<String, String>> entry : smsMap.entrySet()) {
                HashMap<String, String> obj = entry.getValue();
                String taskName = obj.get("taskName");
                String tel = obj.get("tel");
                String userName = obj.get("userName");
                smsUtilService.taskNewSmsService(taskName, tel, userName);
            }

            //保存完后将上传此次上传的单位集合清空
            redisService.del(userId + "batchNum");
            return "保存成功" + "%" + mainTaskId + "%" + taskMain.getMainName();
        } else {
            return "请添加单位";
        }
//        return "200";
    }


    /**
     * 设置 单位任务的时限 ；
     * @param taskUnit
     * @param taskSub
     */
    private void  setTaskUnitTime(TaskUnit taskUnit,TaskSub taskSub)
    {
        if ("1".equals(taskSub.getTimeType())) {
//                            单时限
            taskUnit.setTimeType("1");
            taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
           // taskMain.setTimeLimit(taskSub.getSubTimeLimit());
        } else if ("2".equals(taskSub.getTimeType())) {
            //周期性
            taskUnit.setTimeType("2");
            taskUnit.setPeriod(taskSub.getPeriod());
            taskUnit.setWeek(taskSub.getWeek());
            taskUnit.setMonth(taskSub.getMonth());

            //修改时限错误的bug
            String remindDate = DateUtil.getRemindDate(taskSub.getPeriod(), taskSub.getDay(), taskSub.getWeek(),
                    taskSub.getMonth(), taskSub.getQuarter());
           // taskMain.setTimeLimit(remindDate);
            taskUnit.setTimeLimit(remindDate);


        } else {
            //多时限
            taskUnit.setTimeType("3");
            taskUnit.setTimeLimits(taskSub.getTimeLimits());
            //取出当前多时限的的第一个时限
            if (taskSub.getTimeLimits().contains(",")) {
                String[] split = taskSub.getTimeLimits().split(",");
                taskUnit.setTimeLimit(split[0]);
               // taskMain.setTimeLimit(split[0]);
            } else {
                //只选择了一个
                taskUnit.setTimeLimit(taskSub.getTimeLimits());
              //  taskMain.setTimeLimit(taskSub.getTimeLimits());
            }
        }
    }

  /*  private void saveMain(TaskMain taskMain) {
        taskMain.setSysId(tableService.updateMaxSysId("t_task_main", null));
        getDao().save(taskMain);
    }
*/
    /**
     * 任务导表
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */

    private List<TaskSubFilter> filters = new ArrayList<>();

    public String taskExcel(InputStream inputStream, String name) throws FileNotFoundException {
        //每次导入前将之前的数据清空
        filters.clear();
        //统计错误信息
        String wrong = "";
        List<List<String>> lists = ExcelReaderUtil.readExcel(inputStream, name);
        for (int j = 1; j < lists.size(); j++) {
            List<String> list = lists.get(j);
            if (StringUtils.isNotBlank(list.get(0)) && StringUtils.isNotBlank(list.get(1))) {
                TaskSubFilter taskSubFilter = new TaskSubFilter();
                if (list.size() == 5) {
                    String subName = list.get(0);
                    if (StringUtils.isNotBlank(subName)) {
                        taskSubFilter.setSubName(subName);
                    } else {
                        wrong += "第" + j + "行,请填写子任务名称；\n";
                    }
                    //单位
                    String unit = list.get(1);


                    //子任务时限
                    String subTimeLimit = list.get(3);
                    /*if (StringUtils.isNotBlank(subTimeLimit)) {
                        boolean convertSuccess = true;
                        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                            format.setLenient(false);
                            format.parse(subTimeLimit);
                        } catch (ParseException e) {
                            // e.printStackTrace();
                            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
                            convertSuccess = false;
                        }
                        if (convertSuccess) {
                            taskSubFilter.setSubTimeLimit(subTimeLimit);
                        } else {
                            wrong += "第" + j + "行,子任务时限格式错误；\r\n";
                        }
                    }*/
                    String subDate = "";
                    Calendar ca = Calendar.getInstance();
                    //时间为空就默认当前时间
                    if (StringUtils.isBlank(subTimeLimit)) {
                        subDate = DateUtil.getCurrentDate();
                        ca.setTime(DateUtil.strToDate(subDate));
                    }
                    String cycleValue = "";
                    //子任务时间类型
                    String timeType = list.get(2);
                    switch (timeType) {
                        case "多时限":
                            taskSubFilter.setTimeLimits(subTimeLimit);
                            taskSubFilter.setTimeType("3");
                            break;
                        case "单时限":
                            taskSubFilter.setTimeType("1");
                            taskSubFilter.setSubTimeLimit(subTimeLimit);
                            break;
                        case "天":
                            taskSubFilter.setTimeType("2");
                            taskSubFilter.setPeriod("0");

                            int addnum = 0;
                            try {

                                addnum = Integer.parseInt(subTimeLimit);
                                ca.add(Calendar.DATE, addnum);
                                subDate = DateUtil.DateToStr(ca.getTime());
                            } catch (Exception e) {
                                wrong = "周期性:天，【时限】格式填写错误,正确的格式直接填写天数即可。例如：3";
                                break;
                            }
                            taskSubFilter.setDay(addnum + "");
                            taskSubFilter.setSubTimeLimit(subDate);
                            break;
                        case "周":
                            taskSubFilter.setTimeType("2");
                            taskSubFilter.setPeriod("1");
                            int weeks = ca.get(Calendar.DAY_OF_WEEK);
                            int wk = DateUtil.weekToInt(subTimeLimit);
                            if (wk == 0) {
                                wrong = "周期性：周：【时限】格式填写错误，正确格式例子：星期三";
                                break;
                            }

                            wk = wk + 1;
                            int abs = Math.abs(weeks - wk);
                            ca.add(Calendar.DATE, abs);
                            subDate = DateUtil.DateToStr(ca.getTime());
                            taskSubFilter.setWeek(wk + "");
                            taskSubFilter.setSubTimeLimit(subDate);
                            break;
                        case "月":
                            taskSubFilter.setTimeType("2");
                            taskSubFilter.setPeriod("2");

                            cycleValue = subTimeLimit;
                            int currDay = ca.get(Calendar.DAY_OF_MONTH);
                            int temDay = 0;
                            try {

                                temDay = Integer.parseInt(cycleValue);
                            } catch (Exception e) {
                                wrong = "周期性：月，【格式】格式填写错误，正确的格式例子：03";
                                break;
                            }

                            String currentMonth = DateUtil.getCurrentMonth();

                            if (currDay - temDay > 0) {
                                //提醒日期在  早于 今天，提醒日期设置为下个月的
                                ca.add(Calendar.MONTH, 1);
                                ca.getTime();
                                int maximum = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
                                int year = ca.get(Calendar.YEAR);
                                int month2 = ca.get(Calendar.MONTH) + 1;
                                if (maximum - temDay <= 0) {//考虑2月情况
                                    subDate = year + "-" + month2 + "-" + maximum;
                                } else {
                                    subDate = year + "-" + month2 + "-" + temDay;
                                }
                            } else {
                                subDate = currentMonth + "-" + temDay;
                            }

                            taskSubFilter.setMonth(cycleValue);
                            taskSubFilter.setSubTimeLimit(subDate);
                            break;
                        case "季度":
                            taskSubFilter.setTimeType("2");
                            taskSubFilter.setPeriod("3");
                            cycleValue = subTimeLimit;
                            Date alertDate = DateUtil.strToDate(cycleValue);
                            if (null == alertDate) {
                                wrong = "周期性：季度；【时限】格式填写错误，正确格式为yyyy-MM-dd 例如：2020-12-07";
                                break;
                            }
                            Date currDate = DateUtil.strToDate(DateUtil.getCurrentDate());
                            if (alertDate.compareTo(currDate) > 0) {
                                //提醒日期 是否晚于 今天 如果晚于的话，直接设置。
                                subDate = cycleValue;
                            } else {
                                //下一个季度
                                ca.setTime(alertDate);
                                ca.add(Calendar.MONTH, 3);
                                subDate = DateUtil.DateToStr(ca.getTime());
                            }
                            taskSubFilter.setQuarter(cycleValue);
                            taskSubFilter.setSubTimeLimit(subDate);
                            break;
                        default:
                            taskSubFilter.setTimeType("1");
                            break;

                    }


                    //抄送领导
                    String subCopeTos = list.get(4);
                    if (StringUtils.isNotBlank(subCopeTos)) {
                        //按顿号切割区分领导姓名字符串
                        String[] subCopeTo = subCopeTos.split("、");
                        String subCopeToIds = "";
                        for (String s : subCopeTo) {
                            //根据姓名和用户角色查询用户
                            List<SysLogin> loginList = sysLoginService.getByNameAndRoleId(s, "01");
                            if (loginList.size() <= 0) {
                                wrong += "第" + j + "行（" + s + "）抄送领导姓名不匹配；\n";
                            } else if (loginList.size() > 1) {
                                wrong += "第" + j + "行（" + s + "）抄送领导姓名重复；\n";
                            } else {
                                subCopeToIds += loginList.get(0).getSysId() + ",";
                            }
                        }
                        if (StringUtils.isNotBlank(subCopeToIds)) {
                            subCopeToIds = subCopeToIds.substring(0, subCopeToIds.length() - 1);
                        }
                        taskSubFilter.setSubCopeToIds(subCopeToIds);
                    }
                    //字符串分割
                    if (unit.contains("，")) {
                        //判断是否有逗号，如果有，区分牵头和协办
                        String[] split = unit.split("牵头，");
                        //判断数组长度是否为2
                        if (split.length == 2) {
                            //分割单位
                            String[] leadDeptNames = split[0].split("、"); //牵头单位
                            String leadDeptIds = "";
                            for (String s1 : leadDeptNames) {
                                List<SysDept> sysDeptList = deptService.getByName(s1);
                                if (sysDeptList.size() <= 0 || sysDeptList == null) {
                                    wrong += "第" + j + "行（" + s1 + "）单位名称不匹配；\n";
                                } else if (sysDeptList.size() > 1) {
                                    wrong += "第" + j + "行（" + s1 + "）单位名称重复；\n";
                                } else {
                                    leadDeptIds += (sysDeptList.get(0).getSysId()) + ",";
                                }
                            }
                            if (StringUtils.isNotBlank(leadDeptIds)) {
                                leadDeptIds = leadDeptIds.substring(0, leadDeptIds.length() - 1);
                            }
                            //协办单位
                            String substring = split[1].substring(0, split[1].length() - 2);
                            String[] assistDeptNames = substring.split("、");//协办单位
                            String assistDeptIds = "";
                            for (String assistDeptName : assistDeptNames) {
                                List<SysDept> sysDeptList = deptService.getByName(assistDeptName);
                                if (sysDeptList.size() <= 0 || sysDeptList == null) {
                                    wrong += "第" + j + "行（" + assistDeptName + "）单位名称不匹配；\n";
                                } else if (sysDeptList.size() > 1) {
                                    wrong += "第" + j + "行（" + assistDeptName + "）单位名称重复；\n";
                                } else {
                                    assistDeptIds += sysDeptList.get(0).getSysId() + ",";
                                }
                            }
                            if (StringUtils.isNotBlank(assistDeptIds)) {
                                assistDeptIds = assistDeptIds.substring(0, assistDeptIds.length() - 1);
                            }

                            taskSubFilter.setSubName(subName);
                            taskSubFilter.setLeadDeptIds(leadDeptIds);
                            taskSubFilter.setAssistDeptIds(assistDeptIds);
                            filters.add(taskSubFilter);
                        } else {
                            wrong += "第" + j + "行单位填写格式错误；\n";
                        }
                    } else {
                        //如果没有逗号，都是牵头单位
                        String[] leadDeptNames = unit.split("、"); //牵头单位
                        String leadDeptIds = "";

                        for (String s1 : leadDeptNames) {
                            List<SysDept> sysDeptList = deptService.getByName(s1);
                            if (sysDeptList.size() <= 0 || sysDeptList == null) {
                                wrong += "第" + j + "行（" + s1 + "）单位名称不匹配；\n";
                            } else if (sysDeptList.size() > 1) {
                                wrong += "第" + j + "行（" + s1 + "）单位名称重复；\n";
                            } else {
                                leadDeptIds += (sysDeptList.get(0).getSysId()) + ",";
                            }
                        }
                        if (StringUtils.isNotBlank(leadDeptIds)) {
                            leadDeptIds = leadDeptIds.substring(0, leadDeptIds.length() - 1);
                        }
                        taskSubFilter.setSubName(subName);
                        taskSubFilter.setLeadDeptIds(leadDeptIds);
                        filters.add(taskSubFilter);
                    }
                } else {
                    wrong += "第" + j + "行字段填写不完整；\n";
                }
            }
        }


        if (StringUtils.isNotBlank(wrong)) {
            filters.clear();
            return wrong;
        } else {
            return "200";
        }
    }

    /**
     * 更改审核状态
     *
     * @param taskMainId
     * @return
     */
    public String updateStatus(String taskMainId, String content, String status) {
        TaskMain taskMain = taskMainDao.getById(taskMainId);
        taskMain.setOther(content);
        taskMain.setStatus(status);
        taskMainDao.update(taskMain);
        //更改单位任务状态
        List<TaskUnit> taskUnitList = taskUnitService.getByMainId(taskMainId);
        for (TaskUnit taskUnit : taskUnitList) {
            taskUnit.setStatus(status);
            taskUnitService.update(taskUnit);
        }
        return "200";
    }

    public List<TaskMain> queryByStatus(String s) {
        return taskMainDao.queryByStatus(s);
    }
    /*===================================================以前代码=========================================================*/


    public List<TaskMain> queryFilter(TaskMainFilter filter) {
        List<TaskMain> taskMains = taskMainDao.queryFilter(filter);
        return taskMains;
    }


    /**
     * 修改
     *
     * @return
     */
    /*public String updateTask(TaskMainFilter filter) {
        TaskMain taskMain = taskMainDao.getById(filter.getSysId());
        //判断是否更改过时间
        if (!taskMain.getTimeLimit().equals(filter.getTimeLimit())) {
            String changeTime = changeTime(filter.getCategoryId(), filter.getTimeLimit());
            filter.setTimeLimit(changeTime);
        }
        if (StringUtils.isNotBlank(filter.getMainName())) {
            taskMain.setMainName(filter.getMainName());
        }
        if (StringUtils.isNotBlank(filter.getContent())) {
            taskMain.setContent(filter.getContent());
        }
        if (StringUtils.isNotBlank(filter.getTimeLimit())) {
            taskMain.setTimeLimit(filter.getTimeLimit());
        }
        if (StringUtils.isNotBlank(filter.getFileNumber())) {
            taskMain.setFileNumber(filter.getFileNumber());
        }
        //更新任务
        this.update(taskMain);

        //修改子任务名
        List<TaskSubFilter> subFilterList = filter.getTaskSubFilterList();
        for (TaskSubFilter taskSubFilter : subFilterList) {
            TaskSub taskSub = taskSubService.getById(taskSubFilter.getSysId());
            //查询当前子任务下的单位
            List<TaskUnit> taskUnitList = taskUnitService.getBySubId(taskSubFilter.getSysId());
            for (TaskUnit taskUnit : taskUnitList) {
                taskUnit.setTaskSubName(taskSubFilter.getSubName());
                taskUnitService.update(taskUnit);
            }
            taskSub.setSubName(taskSubFilter.getSubName());
            taskSubService.update(taskSub);
        }
      *//*  //判断是否增加过议题
        if (subFilterList.size() > 0 && subFilterList != null) {
            for (TaskSubFilter taskSubFilter : subFilterList) {
                //保存子任务表
                TaskSub taskSub = new TaskSub();
                taskSub.setTaskMainId(taskMain.getSysId());
                taskSub.setSubName(taskSubFilter.getSubName());
                //保存任务
                taskSubService.save(taskSub);
                List<TaskUnit> taskUnitList = taskSubFilter.getTaskUnitList();
                if (taskUnitList.size() > 0 && taskUnitList != null) {
                    for (TaskUnit taskUnit : taskUnitList) {
                        if (StringUtils.isBlank(filter.getTimeLimit())) {
                            taskUnit.setTimeLimit(taskMain.getTimeLimit());
                        } else {
                            String changeTime = changeTime(filter.getCategoryId(), taskUnit.getTimeLimit());
                            taskUnit.setTimeLimit(changeTime);
                        }
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnitService.save(taskUnit);
                    }
                }
            }
            int t0 = taskUnitService.getCountByType(taskMain.getSysId(),"0");
            int t1 = taskUnitService.getCountByType(taskMain.getSysId(),"1");
            int t2 = taskUnitService.getCountByType(taskMain.getSysId(),"2");
            int t3 = taskUnitService.getCountByType(taskMain.getSysId(),"3");
            int t4 = taskUnitService.getCountByType(taskMain.getSysId(),"4");
            int o = taskUnitService.getCountByStatus(taskMain.getSysId(),"1");
            taskMain.setTypeExplain("待签收: " + t0 + "; 待反馈: " + t1 + "; 已反馈: " + t2 + "; 退回: " + t3 + "; 完成: " + t4);
            taskMain.setOverdueExplain("逾期单位任务: " + o);
            this.update(taskMain);
        }
*//*
        return "200";
    }*/


    /**
     * 删除任务（逻辑删除，将del删除标识字段赋值）
     *
     * @param ids
     * @return
     */
    public String updateDel(List<String> ids, String userId, String ip) {
        //查询当前任务
        try {
            SysLogin login = sysLoginService.getById(userId);
            boolean b = false;
            for (String id : ids) {
                TaskMain taskMain = this.getById(id);
                taskMain.setDel("0");//设置该任务为删除状态
                //将该任务下相关的记录都改为删除
                //单位任务
                List<TaskUnit> taskUnitList = taskUnitService.getByMainId(id);
                for (TaskUnit taskUnit : taskUnitList) {
                    List<TaskBackNew> taskBackList = taskBackNewService.getByTaskUnitId(taskUnit.getSysId());
                    if (ObjectUtils.isNotBlank(taskBackList)) {
                        b = true;
                    }
                    List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(taskUnit.getSysId());
                    //单位个人任务
                    for (TaskUser taskUser : taskUserList) {
                        taskUser.setDel("0");
                        taskUserService.update(taskUser);
                    }
                    taskUnit.setDel("0");
                    taskUnitService.update(taskUnit);
                }
                //子任务
                List<TaskSub> taskSubList = taskSubService.getByMainId(id);
                for (TaskSub taskSub : taskSubList) {
                    //时限记录
                    List<TimeLimit> timeLimitList = timeLimitService.getBySubId(taskSub.getSysId());
                    for (TimeLimit timeLimit : timeLimitList) {
                        timeLimit.setDel("0");
                        timeLimitService.update(timeLimit);
                    }
                    //根据子任务id查询单位任务
                    taskSub.setDel("0");//将子任务状态改为删除
                    taskSubService.update(taskSub);
                }
                //抄送记录
                List<CopeTo> copeToList = copeToService.getByTaskMainId(id);
                for (CopeTo copeTo : copeToList) {
                    copeTo.setDel("0");
                    copeToService.update(copeTo);
                }
                if (b) {
                    //任务有反馈信息,记录删除日志
                    TaskLogEntity taskLog = new TaskLogEntity();
                    taskLog.setDateTime(DateUtils.getDateTime());
                    taskLog.setUserId(userId);
                    taskLog.setUserName(login.getUsername());
                    taskLog.setIp(ip);
                    taskLog.setTaskName(taskMain.getMainName());
                    taskLog.setTaskType("1");//主任务
                    taskLog.setContent("删除任务");
                    taskLog.setTaskId(taskMain.getSysId());
                    taskLogEntityService.save(taskLog);
                }
                this.update(taskMain);

            }
        /*taskUserService.batchDeleteIds(ids);
        taskUnitService.batchDeleteIds(ids);
        taskSubService.batchDeleteIds(ids);
        taskMainDao.batchDelete(ids);
        */
            return "200";
        } catch (Exception e) {
            e.printStackTrace();
            return "500";
        }
    }

    /**
     * 添加子事项
     *
     * @param filter
     * @return
     * @throws Exception
     */
    public String addTaskSub(TaskSubFilter filter) throws Exception {

        HashMap<String, HashMap<String, String>> smsMap = new HashMap<>();//发短信专用


        { //每月
            String userId = filter.getUserId();
            int year = Calendar.getInstance().get(Calendar.YEAR);//年
            int month = Calendar.getInstance().get(Calendar.MONTH) + 1;//月
            int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);//日
            SysUser user = sysUserDao.getById(userId);
            TaskMain taskMain = taskMainDao.getById(filter.getTaskMainId());
            TaskSub taskSub = new TaskSub();
            taskSub.setStatus(taskMain.getStatus());//子任务状态与主任务相同
            taskSub.setTaskMainId(taskMain.getSysId());
            if (StringUtils.isBlank(filter.getSubName())) {
                //如果子事项名称为空，将主任务名称赋值到子任务名字
                taskSub.setSubName(taskMain.getMainName());
            } else {
                taskSub.setSubName(filter.getSubName());
            }

            /*if (StringUtils.isBlank(filter.getSubTimeLimit())) {
                //如果子事项时限为空，将主任务时限赋值到子任务
                if ("1".equals(taskMain.getTimeType())) {
                    //时限
                    taskSub.setTimeType("1");
                    taskSub.setSubTimeLimit(taskMain.getTimeLimit());
                } else if ("2".equals(taskMain.getTimeType())) {
                    taskSub.setTimeType("2");
                    taskSub.setPeriod(taskMain.getPeriod());
                    taskSub.setDay(taskMain.getDay());
                    taskSub.setWeek(taskMain.getWeek());
                    taskSub.setMonth(taskMain.getMonth());
                    taskSub.setQuarter(taskMain.getQuarter());
                } else {
                    taskSub.setTimeType("3");
                    taskSub.setTimeLimits(taskMain.getTimeLimits());
                }
            } else {
                //单时限
                taskSub.setTimeType("1");
                taskSub.setSubTimeLimit(filter.getSubTimeLimit());
            }*/
            //设置子任务时限
            TaskMainFilter mainFilter = new TaskMainFilter();
            BeanUtils.copyProperties(taskMain, mainFilter);

            setTaskSubTime(filter, taskSub, mainFilter);
            if (taskMain.getImp() == 1) {
                taskSub.setImp(1);
            }

            taskSubService.save(taskSub, user.getSysId());
            TimeLimit timeLimit = new TimeLimit();
            timeLimit.setTaskSubId(taskSub.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
            timeLimit.setTimeType(taskSub.getTimeType());
            timeLimit.setPeriod(taskSub.getPeriod());
            timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
            timeLimit.setTimeLimits(taskSub.getTimeLimits());
            timeLimit.setDay(taskSub.getDay());
            timeLimit.setWeek(taskSub.getWeek());
            timeLimit.setMonth(taskSub.getMonth());
            timeLimit.setQuarter(taskSub.getQuarter());
            timeLimit.setState("1");
            timeLimitService.save(timeLimit, user.getSysId());
            //判断子事项是否有抄送领导
            if (ObjectUtils.isNotBlank(filter.getSubCopeToIds())) {
                //如果不为空
                String subCopeToIds = filter.getSubCopeToIds();
                //切割抄送领导字符串
                String[] split = subCopeToIds.split(",");
                for (String subCopeToId : split) {
                    CopeTo copeTo = new CopeTo();
                    copeTo.setLeaderId(subCopeToId);
                    copeTo.setTaskMainId(taskMain.getSysId());
                    copeTo.setSubMainId(taskSub.getSysId());
                    copeTo.setStatus("0");
                    copeToService.save(copeTo, user.getSysId());
                }
            }

            //取出牵头单位集合
            String leadDeptIds = filter.getLeadDeptIds();
            if (StringUtils.isBlank(leadDeptIds)) {
                throw new Exception("请添加单位");
            } else {
                String[] strings = leadDeptIds.split(",");
                for (String leadDeptId : strings) {
                    SysDept dept = sysDeptService.getById(leadDeptId);
                    TaskUnit taskUnit = new TaskUnit();
                    taskUnit.setDeptId(leadDeptId);
                    taskUnit.setUnitType("1");//牵头单位
                    taskUnit.setTaskMainName(taskMain.getMainName());
                    taskUnit.setTaskSubId(taskSub.getSysId());
                    taskUnit.setType("0");
                    taskUnit.setTaskMainId(taskMain.getSysId());
                    taskUnit.setTaskSubName(taskSub.getSubName());
                    taskUnit.setCategoryId(taskMain.getCategoryId());
                    taskUnit.setStatus(taskSub.getStatus());
                    if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                        taskUnit.setTimeType("1");
                        taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                        taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                    } else if ("2".equals(taskSub.getTimeType())) {
                        //周期性
                        taskUnit.setTimeType("2");
                        taskUnit.setPeriod(taskSub.getPeriod());
                        taskUnit.setWeek(taskSub.getWeek());
                        taskUnit.setMonth(taskSub.getMonth());

                        String remindDate = DateUtil.getRemindDate(taskSub.getPeriod(), taskSub.getDay(), taskSub.getWeek(),
                                taskSub.getMonth(), taskSub.getQuarter());
                        taskMain.setTimeLimit(remindDate);
                        taskUnit.setTimeLimit(remindDate);

                    } else {
                        //多时限
                        taskUnit.setTimeType("3");
                        taskUnit.setTimeLimits(taskSub.getTimeLimits());
                        //取出当前多时限的的第一个时限
                        if (taskSub.getTimeLimits().contains(",")) {
                            String[] split = taskSub.getTimeLimits().split(",");
                            taskUnit.setTimeLimit(split[0]);
                            taskMain.setTimeLimit(split[0]);
                        } else {
                            //只选择了一个
                            taskUnit.setTimeLimit(taskSub.getTimeLimits());
                            taskMain.setTimeLimit(taskSub.getTimeLimits());
                        }
                    }
                    taskUnit.setDeptName(dept.getDeptName());
                    //设置为待办
                    taskUnit.setState("0");
                    //第一轮
                    taskUnit.setTimeRound("1");
                    if (taskMain.getImp() == 1) {
                        taskUnit.setImp(1);
                    }
                    taskUnitService.save(taskUnit, user.getSysId());
                    //记录任务流程
                    //发送短信。查询当前单位的领导
                    SysUserFilter userFilter = new SysUserFilter();
                    userFilter.setRoleId("02");
                    userFilter.setDeptId(dept.getSysId());
                    List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                    for (SysLogin sysLogin : loginList) {
                        SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                        String mobile = sysUser.getMobile();
                        if (StringUtils.isNotBlank(mobile)) {
                            // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                            HashMap<String, String> map = new HashMap<>();
                            map.put("userName", sysUser.getName());
                            map.put("tel", sysUser.getMobile());
                            map.put("taskName", taskUnit.getTaskMainName());
                            smsMap.put(sysLogin.getSysId(), map);
                        }
                    }
                    TaskLogNew taskLogNew = new TaskLogNew();
                    taskLogNew.setTaskUnitId(taskUnit.getSysId());
                    String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + dept.getDeptName() + "牵头";
                    taskLogNew.setContent(s);
                    taskLogNewService.save(taskLogNew, user.getSysId());
                }
                this.update(taskMain);
            }
            //取出协办单位
            String assistDeptIds = filter.getAssistDeptIds();
            if (StringUtils.isNotBlank(assistDeptIds)) {
                String[] strings = assistDeptIds.split(",");
                for (String assistDeptId : strings) {
                    SysDept dept = sysDeptService.getById(assistDeptId);

                    TaskUnit taskUnit = new TaskUnit();
                    taskUnit.setDeptId(assistDeptId);
                    taskUnit.setUnitType("2");//xieban单位
                    taskUnit.setTaskSubId(taskSub.getSysId());
                    taskUnit.setType("0");
                    taskUnit.setTaskMainId(taskMain.getSysId());
                    taskUnit.setTaskSubName(taskSub.getSubName());
                    taskUnit.setCategoryId(taskMain.getCategoryId());
                    taskUnit.setTaskMainName(taskMain.getMainName());
                    taskUnit.setDeptName(dept.getDeptName());
                    taskUnit.setStatus(taskSub.getStatus());
                    if ("1".equals(taskSub.getTimeType())) {
                        taskUnit.setTimeType("1");
                        //判断协办单位是否有单独时限
                        if (StringUtils.isNotBlank(taskMain.getLessDays())) {
                            String format = xiebanLimit(taskSub.getSubTimeLimit(), taskMain.getLessDays());
                            taskUnit.setTimeLimit(format);
                        } else {
                            taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                        }
                    } else if ("2".equals(taskSub.getTimeType())) {
                        //周期性
                        taskUnit.setTimeType("2");
                        taskUnit.setPeriod(taskSub.getPeriod());
                        taskUnit.setWeek(taskSub.getWeek());
                        taskUnit.setMonth(taskSub.getMonth());
                        String remindDate = DateUtil.getRemindDate(taskSub.getPeriod(), taskSub.getDay(),
                                taskSub.getWeek(), taskSub.getMonth(), taskSub.getQuarter());
                        if ("0".equals(taskSub.getPeriod())) {

                            taskMain.setTimeLimit(remindDate);
                        }
                        taskUnit.setTimeLimit(remindDate);
                    } else {
                        //多时限
                        taskUnit.setTimeType("3");
                        taskUnit.setTimeLimits(taskSub.getTimeLimits());
                        //取出当前多时限的的第一个时限
                        if (taskSub.getTimeLimits().contains(",")) {
                            String[] split = taskSub.getTimeLimits().split(",");
                            if (StringUtils.isBlank(taskMain.getLessDays())) {
                                taskUnit.setTimeLimit(split[0]);
                            } else {
                                taskUnit.setTimeLimit(xiebanLimit(split[0], taskMain.getLessDays()));
                            }
                        } else {
                            //只选择了一个
                            String format = xiebanLimit(taskSub.getSubTimeLimit(), taskMain.getLessDays());
                            taskUnit.setTimeLimit(format);
                        }
                    }
                    taskUnit.setDeptName(dept.getDeptName());
                    //设置为待办
                    taskUnit.setState("0");
                    //第一轮
                    taskUnit.setTimeRound("1");
                    if (taskMain.getImp() == 1) {
                        taskUnit.setImp(1);
                    }
                    taskUnitService.save(taskUnit, user.getSysId());
                       /* TimeLimit timeLimit = new TimeLimit();
                        timeLimit.setTaskUnitId(taskUnit.getSysId());
                        timeLimit.setTimeType(taskSub.getTimeType());
                        timeLimit.setPeriod(taskSub.getPeriod());
                        timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                        timeLimit.setTimeLimits(taskSub.getTimeLimits());
                        timeLimit.setState("1");
                        timeLimitService.save(timeLimit);*/
                    //记录任务流程
                    //发送短信。查询当前单位的领导
                    SysUserFilter userFilter = new SysUserFilter();
                    userFilter.setRoleId("02");
                    userFilter.setDeptId(dept.getSysId());
                    List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                    for (SysLogin sysLogin : loginList) {
                        SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                        String mobile = sysUser.getMobile();
                        if (StringUtils.isNotBlank(mobile)) {
                            // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                            HashMap<String, String> map = new HashMap<>();
                            map.put("userName", sysUser.getName());
                            map.put("tel", sysUser.getMobile());
                            map.put("taskName", taskUnit.getTaskMainName());
                            smsMap.put(sysLogin.getSysId(), map);
                        }
                    }

                    TaskLogNew taskLogNew = new TaskLogNew();
                    taskLogNew.setTaskUnitId(taskUnit.getSysId());
                    String s = user.getName() + "立项： " + taskSub.getSubName() + ",由" + dept.getDeptName() + "协办";
                    taskLogNew.setContent(s);
                    taskLogNewService.save(taskLogNew, user.getSysId());
                }
            }
            int t0 = taskUnitService.getCountByType(taskMain.getSysId(), "0");
            int t1 = taskUnitService.getCountByType(taskMain.getSysId(), "1");
            int t2 = taskUnitService.getCountByType(taskMain.getSysId(), "2");
            int t3 = taskUnitService.getCountByType(taskMain.getSysId(), "3");
            int t4 = taskUnitService.getCountByType(taskMain.getSysId(), "4");
            int t5 = taskUnitService.getCountByType(taskMain.getSysId(), "5");
            int o = taskUnitService.getCountByStatus(taskMain.getSysId(), "1");
            taskMain.setTypeExplain("待签收: " + t0 + "；已签收：" + t5 + " ；待反馈: " + t1 + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);
            taskMain.setOverdueExplain("逾期单位任务: " + o);
            this.update(taskMain);

            //发送短信
            for (Map.Entry<String, HashMap<String, String>> entry : smsMap.entrySet()) {
                HashMap<String, String> obj = entry.getValue();
                String taskName = obj.get("taskName");
                String tel = obj.get("tel");
                String userName = obj.get("userName");
                smsUtilService.taskNewSmsService(taskName, tel, userName);
            }

        }


        return "200";
    }

    public List<TaskMain> getUnDoneFilter(TaskMainFilter taskMainFilter) {
        List<TaskMain> taskMains = taskMainDao.unDoneFilter(taskMainFilter);
        List<TaskMain> taskMainList = new ArrayList<>();
        String deptId = taskMainFilter.getDeptId();
        if (StringUtils.isNotBlank(deptId)) {
            String[] split = deptId.split(",");
            for (String s : split) {
                if (ObjectUtils.isNotBlank(taskMains)) {
                    for (TaskMain taskMain : taskMains) {
                        List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                        for (TaskUnit taskUnit : taskUnits) {
                            if (s.equals(taskUnit.getDeptId())) {
                                taskMainList.add(taskMain);
                                continue;
                            }
                        }
                    }
                }
            }
        } else {
            return taskMains;
        }
        return taskMainList;
    }

    /**
     * 督查对反馈内容进行判断
     *
     * @param
     * @return
     */
    public String updateBackNew(TaskBackNewFilter backNewFilter) {
        TaskBackNew taskBackNew = taskBackNewService.getById(backNewFilter.getSysId());
        TaskUnit taskUnit = taskUnitService.getById(taskBackNew.getTaskUnitId());
        TaskMain taskMain = taskMainDao.getById(taskUnit.getTaskMainId());
        TaskCategory taskCategory = taskCategoryService.getById(taskMain.getCategoryId());
        String userId = "";
        if (StringUtils.isNotBlank(backNewFilter.getUserId())) {
            userId = backNewFilter.getUserId();
        } else {
            userId = SysUserUtils.getUserId();
        }
        SysUser user = sysUserDao.getById(userId);
        String status = backNewFilter.getStatus();
        //判断是否办结 任务办结修改任务的状态
        if ("1".equals(backNewFilter.getStatus())) {
            taskBackNew.setStatus("1");
            //将单位任务状态改为完成
            if ("3".equals(taskUnit.getType()) || "7".equals(taskUnit.getType()) || "8".equals(taskUnit.getType())) {
                taskUnit.setType("9");//
            } else {

                taskUnit.setType("4");
            }
            taskUnit.setComment(backNewFilter.getComment());// 任务评价
            //判断当前事项类型
            /* if ("1".equals(taskCategory.getType())) {*/
            //判断当前任务是否逾期

           /* if (StringUtils.isBlank(taskUnit.getOverdueDay())) { 暂时不需要评分，先注释
                //如果 为空表示为未逾期,得10分
                taskUnit.setScore(taskCategory.getType());
            } else {
                //逾期得0分
                taskUnit.setScore("0");
            }*/
      /*      } else {
                //目前只有 一种方案。后期修改
                //判断当前任务是否逾期
                if (StringUtils.isNotBlank(taskUnit.getOverdueDay())) {
                    //如果 为空表示为未逾期,得10分
                    taskUnit.setScore("10");
                } else {
                    //逾期得0分
                    taskUnit.setScore("0");
                }
            }*/
            taskUnit.setEndTime(DateUtils.getDateTime());
            taskUnitService.update(taskUnit);
            //查询当前子任务的所有牵头单位的任务是否都已近办结了
            TaskUnitFilter filter = new TaskUnitFilter();
            filter.setTaskSubId(taskUnit.getTaskSubId());
            filter.setUnitType("1");
            List<TaskUnit> unitList = taskUnitService.queryFilter(filter);
            //如果只有一个牵头单位且办结
            if (unitList.size() == 1) {
                //将这次反馈内容复制到子任务汇总中
                TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());
                taskSub.setSubContent(taskBackNew.getContent());
                taskSub.setSubProblem(taskBackNew.getProblem());
                taskSub.setSubPlan(taskBackNew.getPlan());
                taskSub.setSubSituationFile(taskBackNew.getFile());
                taskSub.setFileName(taskBackNew.getFileName());
                taskSubService.update(taskSub);
            }
            filter.setType("4");
            List<TaskUnit> unitList1 = taskUnitService.queryFilter(filter);
            //判断周期性任务是否结束
            if ("1".equals(backNewFilter.getEnd())) {
                //结束周期
                List<TimeLimit> timeLimits = timeLimitService.getBySubId(filter.getTaskSubId());
                for (TimeLimit timeLimit : timeLimits) {
                    timeLimit.setState("0");
                    //结束周期
                    timeLimitService.update(timeLimit);
                }
            }
            if (unitList.size() == unitList1.size()) {
                //全部牵头单位的任务完成，协办单位的任务也会转为完成
                filter = new TaskUnitFilter();
                filter.setTaskSubId(taskUnit.getTaskSubId());
                filter.setUnitType("2");
                List<TaskUnit> unitList2 = taskUnitService.queryFilter(filter);
                for (TaskUnit unit : unitList2) {
                    unit.setScore(taskUnit.getScore());
                    unit.setType("4");
                    taskUnitService.update(unit);
                }
                TaskSub taskSub = taskSubService.getById(filter.getTaskSubId());
                taskSub.setType("1");
                taskSubService.update(taskSub);
            }
            //如果牵头单位办结后，单位任务下的所有任务都会办结
            List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(taskUnit.getSysId());
            for (TaskUser taskUser : taskUsers) {
                taskUser.setStatus("4");
                taskUserService.update(taskUser);
            }
            status = "办结";
        } else if ("2".equals(status)) {
            //退回重办
            taskBackNew.setStatus("2");
            taskUnit.setType("3");
            if (StringUtils.isBlank(taskUnit.getBackNum())) {
                taskUnit.setBackNum("1");
            } else {
                int i = Integer.parseInt(taskUnit.getBackNum());
                i++;
                taskUnit.setBackNum(i + "");
            }
            taskUnitService.update(taskUnit);
            status = "退回重办";
        } else {
            return "500";
        }
        //处理后将状态改为正常
        //判断当前任务还有没有已反馈的单位任务
        int countByType = taskUnitService.getCountByType(taskMain.getSysId(), "2");
        if (countByType <= 0) {
            taskMain.setStatus("2");
        }

        //查询当前主任务所有的单位任务是否全部完成了
        TaskUnitFilter filter = new TaskUnitFilter();
        filter.setTaskMainId(taskMain.getSysId());
        List<TaskUnit> unitList = taskUnitService.queryFilter(filter);
        filter.setType("4");
        List<TaskUnit> unitList1 = taskUnitService.queryFilter(filter);
        if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
            taskMain.setOverdueDeptState("1");
        } else {
            //不是单位重大事项
            if (unitList.size() == unitList1.size()) {
                //全部子任务完成
                taskMain.setStatus("4");
            }
        }
        //记录任务日志
        //添加任务日志
        SysUser byId = sysUserDao.getById(taskBackNew.getCreateUser());
        TaskLogNew taskLogNew = new TaskLogNew();
        taskLogNew.setTaskUnitId(taskUnit.getSysId());
        taskLogNew.setUserId(taskBackNew.getCreateUser());
        String content = user.getName() + "办理" + byId.getName() + "的反馈信息" + status;
        taskLogNew.setContent(content);
        taskLogNewService.save(taskLogNew, userId);
        taskMainDao.update(taskMain);
        int t0 = taskUnitService.getCountByType(taskMain.getSysId(), "0");
        int t1 = taskUnitService.getCountByType(taskMain.getSysId(), "1");
        int t2 = taskUnitService.getCountByType(taskMain.getSysId(), "2");
        int t3 = taskUnitService.getCountByType(taskMain.getSysId(), "3");
        int t4 = taskUnitService.getCountByType(taskMain.getSysId(), "4");
        int t5 = taskUnitService.getCountByType(taskMain.getSysId(), "5");
        int o = taskUnitService.getCountByStatus(taskMain.getSysId(), "10");
        taskMain.setTypeExplain("待签收: " + t0 + "；已签收：" + t5 + " ；待反馈: " + t1 + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);

        taskMain.setOverdueExplain("逾期单位任务: " + o);
        this.update(taskMain);
        return "200";
    }


    /**
     * 协办的时限
     *
     * @param limit
     * @param days
     * @return
     * @throws ParseException
     */
    private String xiebanLimit(String limit, String days) throws ParseException {
        Date date = simdate1.parse(limit);
        long time = date.getTime();
        int day = Integer.parseInt(days);
        long l = time - day * (1000 * 60 * 60 * 24);
        Date date1 = new Date(l);
        String format = simdate1.format(date1);
        return format;
    }

    public List<TaskMain> queryDBOverdueDept(TaskMainFilter filter) {
        return taskMainDao.queryDBOverdueDept(filter);
    }

    public List<TaskMain> queryZBOverdueDept(TaskMainFilter filter) {
        return taskMainDao.queryZBOverdueDept(filter);
    }

    public List<TaskMain> queryWCOverdueDept(TaskMainFilter filter) {
        return taskMainDao.queryWCOverdueDept(filter);
    }

    public List<TaskMain> queryOverdueDept(TaskMainFilter filter) {
        return taskMainDao.queryOverdueDept(filter);
    }

    /**
     * 导出Excel
     *
     * @param filter
     * @return
     */
    public HSSFWorkbook getTaskExcel(TaskMainFilter filter) {
        Paging page = new Paging();
        page.setSortCol("sysId");
        page.setSortVal("desc");
        page.setPageSize(300);
        filter.setPaging(page);
        TaskMain taskMain = this.getById(filter.getSysId());
        //创建一个对应的Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("督查情况表");//创建Excel中的sheet
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中格式
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        //第一列为任务名
        HSSFRow rowName = sheet.createRow(0);
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 6);// 下标从0开始 起始行号，终止行号， 起始列号，终止列号
        sheet.addMergedRegion(region);
        HSSFCell rowNameCell = rowName.createCell(0);
        rowNameCell.setCellValue(taskMain.getMainName());
        rowNameCell.setCellStyle(style);
        //第二列为表头
        HSSFRow row = sheet.createRow(1);

        HSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("序号");
        cell1.setCellStyle(style);
        List<String> headers = new ArrayList<>();
        headers.add("事项内容");
        headers.add("承办单位");
        headers.add("督办结果");
        headers.add("存在问题");
        headers.add("下步措施");
        headers.add("办结情况");
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i + 1);
            cell.setCellValue(headers.get(i));//设置表头
            cell.setCellStyle(style);
            sheet.autoSizeColumn((short) i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 15 / 10);
        }
        String taskName = "";  //事项内容
        String departName = ""; //承办单位
        String overdueResult = ""; //督办结果
        String subProblem = ""; //存在问题
        String subPlan = ""; //下步计划
        String type = "";   //办结情况
        //查询承办单位名称
        TaskSubFilter subFilter = new TaskSubFilter();
        subFilter.setTaskMainId(filter.getSysId());
        List<TaskSub> taskSubList = taskSubService.queryFilter(subFilter);
        int rows = 2;
        for (int i = 0; i < taskSubList.size(); i++) {
            taskName = taskSubList.get(i).getSubName();
            row = sheet.createRow(rows);
            HSSFCell numCell = row.createCell(0);
            numCell.setCellValue(rows - 1);//设置序号
            numCell.setCellStyle(style);//居中样式
            //事项内容
            HSSFCell nameCell = row.createCell(1);
            nameCell.setCellValue(taskName);
            nameCell.setCellStyle(style2); //样式

            List<TaskUnit> taskUnits = taskUnitService.getBySubId(taskSubList.get(i).getSysId());
            for (TaskUnit taskUnit : taskUnits) {
                departName += taskUnit.getDeptName() + ",";
            }
            departName = departName.substring(0, departName.length() - 1);
            HSSFCell deptCell = row.createCell(2);
            deptCell.setCellValue(departName);
            deptCell.setCellStyle(style2); //样式
            overdueResult = taskSubList.get(i).getSubSituation();
            HSSFCell resultCell = row.createCell(3);
            resultCell.setCellValue(overdueResult);
            resultCell.setCellStyle(style2); //样式
            subProblem = taskSubList.get(i).getSubProblem();
            HSSFCell subProblemCell = row.createCell(4);
            subProblemCell.setCellValue(subProblem);
            subProblemCell.setCellStyle(style2); //样式
            subPlan = taskSubList.get(i).getSubPlan();
            HSSFCell subPlanCell = row.createCell(5);
            subPlanCell.setCellValue(subProblem);
            subPlanCell.setCellStyle(style2); //样式
            if (StringUtils.isNotBlank(taskSubList.get(i).getType())) {
                if ("1".equals(taskSubList.get(i).getType())) {
                    //办结
                    type = "已办结";
                } else if ("2".equals(taskSubList.get(i).getType())) {
                    type = "逾期";
                }
            } else {
                //空
                type = "未办结";
            }
            HSSFCell typeCell = row.createCell(6);
            typeCell.setCellValue(type);
            typeCell.setCellStyle(style); //样式
            rows++;
//            row = sheet.createRow(rows);
        }
        return workbook;
    }


    /**
     * 修改主任务
     *
     * @param filter
     * @return
     */
    public String updateTaskMain(TaskMainFilter filter) {
        TaskMain taskMain = taskMainDao.getById(filter.getSysId());
        if (ObjectUtils.isNotBlank(taskMain)) {
            taskMain.setMainName(filter.getMainName());
            taskMain.setContent(filter.getContent());
            taskMain.setTimeLimit(filter.getTimeLimit());
            List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
            for (TaskUnit taskUnit : taskUnits) {
                taskUnit.setTaskMainName(filter.getMainName());
                if (!filter.getTimeLimit().equals(taskMain.getTimeLimit())) {
                    //更改过时间
                    taskUnit.setTimeLimit(filter.getTimeLimit());
                }
                taskUnitService.update(taskUnit);
            }
//            taskMain.setCategoryId(filter.getCategoryId());
            if (StringUtils.isNotBlank(filter.getFile())) {
                taskMain.setFile(filter.getFile());
                taskMain.setFileName(filter.getFileName());
            }
            taskMainDao.update(taskMain);
            return "200";
        } else {
            return "500";
        }
    }


    /**
     * 查询已删除的 任务 回收站
     *
     * @param filter
     * @return
     */
    public List<TaskMain> queryDelTask(TaskMainFilter filter) {
        return taskMainDao.queryDelTask(filter);
    }

    /**
     * 恢复已删除的任务
     *
     * @param taskMainId
     * @return
     */
    public String updateRecover(String taskMainId) {
        TaskMain taskMain = taskMainDao.getById(taskMainId);
        if (ObjectUtils.isNotBlank(taskMain)) {
            //已删除的单位任务
            List<TaskUnit> taskUnitList = taskUnitService.getByMainIdDel(taskMainId);
            for (TaskUnit taskUnit : taskUnitList) {
                List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdDel(taskUnit.getSysId());
                //单位个人任务
                for (TaskUser taskUser : taskUserList) {
                    taskUser.setDel(null);
                    taskUserService.update(taskUser);
                }
                taskUnit.setDel(null);
                taskUnitService.update(taskUnit);
            }
            //子任务
            List<TaskSub> taskSubList = taskSubService.getByMainIdDel(taskMainId);
            for (TaskSub taskSub : taskSubList) {
                //时限记录
                List<TimeLimit> timeLimitList = timeLimitService.getBySubIdDel(taskSub.getSysId());
                for (TimeLimit timeLimit : timeLimitList) {
                    timeLimit.setDel(null);
                    timeLimitService.update(timeLimit);
                }
                //根据子任务id查询单位任务
                taskSub.setDel(null);//将子任务状态改为删除
                taskSubService.update(taskSub);
            }
            //抄送记录
            List<CopeTo> copeToList = copeToService.getByTaskMainIdDel(taskMainId);
            for (CopeTo copeTo : copeToList) {
                copeTo.setDel(null);
                copeToService.update(copeTo);
            }
            taskMain.setDel(null);
            this.update(taskMain);
            return "200";
        } else {
            return "500";
        }
    }

    /**
     * 删除单位任务
     *
     * @param
     * @return
     */
    @Transactional
    public String updateDelUnit(String taskSubId) {
        //查询当前单位任务
        //  TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
        // String taskSubId =taskUnit.getTaskSubId();
//        List<TaskUnit> taskUnits = taskUnitService.getBySubId(taskSubId);
        TaskSub taskSubInfo = taskSubService.getById(taskSubId);

        TaskUnitFilter filter = new TaskUnitFilter();
        filter.setTaskSubId(taskSubId);

        //  String taskMainId = taskUnit.getTaskMainId();
        List<TaskSub> ListSubs = taskSubService.getByMainId(taskSubInfo.getTaskMainId());
        if (ObjectUtils.isNotBlank(ListSubs)) {
            List<TaskUnit> taskUnits = taskUnitService.queryListUnit(filter);
            try {

                for (TaskUnit unit : taskUnits) {
                    unit.setDel("0");

                    List<TaskUser> byTaskUnitId = taskUserService.getByTaskUnitId(unit.getSysId());
                    if (ObjectUtils.isNotBlank(byTaskUnitId)) {

                        byTaskUnitId.forEach(o -> o.setDel("0"));
                        taskUserService.batchUpdate(byTaskUnitId);
                    }
                }
                taskUnitService.batchUpdate(taskUnits);
                TaskSub taskSub = taskSubService.getById(taskSubId);
                taskSub.setDel("0");
                taskSubService.update(taskSub);

                if (ListSubs.size() == 1) {
                    //只有一个子任务 ,删掉子任务 登陆所有任务删除；
                    TaskMain taskMain = this.getById(taskSub.getTaskMainId());
                    taskMain.setDel("0");
                    this.update(taskMain);

                }


                return 200 + "";
            } catch (Exception e) {
                return "500";
            }

        }

        return "500";




        /*if (ObjectUtils.isNotBlank(taskUnit)) {
            List<Map<String, Object>> maps = taskUnitService.getByOldTaskUnit(taskUnit.getTaskSubId(), taskUnit.getDeptId());
            if (ObjectUtils.isNotBlank(maps)) {
                //不止一轮
                for (Map<String, Object> map : maps) {
                    TaskUnit unit = (TaskUnit) map.get("taskUnit");
                    List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(unit.getSysId());
                    //单位个人任务
                    for (TaskUser taskUser : taskUserList) {
                        taskUser.setDel("0");
                        taskUserService.update(taskUser);
                    }
                    unit.setDel("0");
                    taskUnitService.update(unit);
                    //将该单位任务的历史轮次也删除
                }
            } else {
                //只有一轮任务
                List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(taskUnit.getSysId());
                //单位个人任务
                for (TaskUser taskUser : taskUserList) {
                    taskUser.setDel("0");
                    taskUserService.update(taskUser);
                }
                taskUnit.setDel("0");
                taskUnitService.update(taskUnit);
                //将该单位任务的历史轮次也删除
            }
            //查询当前任务的子任务
            List<TaskUnit> taskUnits = taskUnitService.getBySubId(taskUnit.getTaskSubId());
            if (ObjectUtils.isBlank(taskUnits)) {
                //如果子任务单位任务为空,将该子任务删除
                TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());
                taskSub.setDel("0");
                taskSubService.update(taskSub);
            }
            return "200";
        } else {
            return "500";
        }*/
    }

    /**
     * 子任务添加单位
     *
     * @param filter
     * @return
     */
    public String addTaskUnit(TaskSubFilter filter) throws ParseException {

        HashMap<String, HashMap<String, String>> smsMap = new HashMap<>();//发短信专用


        //每月
        String userId = "";

        if (StringUtils.isNotBlank(filter.getUserId())) {
            userId = filter.getUserId();
        } else {
            userId = SysUserUtils.getUserId();
        }

        SysUser user = sysUserDao.getById(userId);
        TaskSub taskSub = taskSubService.getById(filter.getSysId());
        TaskMain taskMain = taskMainDao.getById(taskSub.getTaskMainId());
        //取出牵头单位集合
        String leadDeptIds = filter.getLeadDeptIds();
        if (StringUtils.isNotBlank(leadDeptIds)) {
            String[] strings = leadDeptIds.split(",");
            for (String leadDeptId : strings) {
                SysDept dept = sysDeptService.getById(leadDeptId);
                TaskUnit taskUnit = new TaskUnit();
                taskUnit.setDeptId(leadDeptId);
                taskUnit.setUnitType("1");//牵头单位
                taskUnit.setTaskMainName(taskMain.getMainName());
                taskUnit.setTaskSubId(taskSub.getSysId());
                taskUnit.setType("0");
                taskUnit.setTaskMainId(taskMain.getSysId());
                taskUnit.setTaskSubName(taskSub.getSubName());
                taskUnit.setCategoryId(taskMain.getCategoryId());
                taskUnit.setStatus(taskSub.getStatus());

                taskUnit.setTimeType(taskSub.getTimeType());
                taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                taskUnit.setTimeLimits(taskSub.getTimeLimits());
                taskUnit.setPeriod(taskSub.getPeriod());
                taskUnit.setDay(taskSub.getDay());
                taskUnit.setWeek(taskSub.getWeek());
                taskUnit.setMonth(taskSub.getMonth());
                taskUnit.setQuarter(taskSub.getQuarter());
                taskUnit.setImp(taskSub.getImp());
                //  taskUnit.set


                /*if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                    taskUnit.setTimeType("1");
                    taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                    taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                } else if ("2".equals(taskSub.getTimeType())) {
                    //周期性
                    taskUnit.setTimeType("2");
                    taskUnit.setPeriod(taskSub.getPeriod());
                    taskUnit.setWeek(taskSub.getWeek());
                    taskUnit.setMonth(taskSub.getMonth());
                    if ("0".equals(taskSub.getPeriod())) {
                        String time = changeTime(taskSub.getDay());
                        //如果是按天的周期性反馈。
                        int dayInt = Integer.parseInt(taskSub.getDay());
                       *//* long millis = System.currentTimeMillis();//当前时间的毫秒值
                        long timeLimitIong = millis + dayInt * 3600 * 24 * 1000;
                        String timeLimitDay = simdate1.format(timeLimitIong);//当前任务时限*//*
                        taskUnit.setTimeLimit(time);
                        taskMain.setTimeLimit(time);
                    } else if ("1".equals(taskSub.getPeriod())) {
                        //如果是每周获取当前日期是周几
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(new Date());
                        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                        if (w < 0) {
                            w = 7;
                        }
                        //判断周期性与当前星期的大小
                        if (w < Integer.parseInt(taskSub.getWeek())) {
                            //如果小于，时限为本周周几
                            Map<String, String> weekDate = WeekDayUtil.getWeekDate();
                            String[] dates = WeekDayUtil.getDates(weekDate.get("mondayDate"), weekDate.get("sundayDate"), taskSub.getWeek());
                            taskUnit.setTimeLimit(dates[0]);
                            taskMain.setTimeLimit(dates[0]);
                        } else {
                            //如果相同或者大于。时限为下周周几
                            Date now = new Date();
                            Map<String, String> nextWeek = WeekDayUtil.getNextWeek(simdate1.format(now));
                            String[] dates = WeekDayUtil.getDates(nextWeek.get("beginDateNext"), nextWeek.get("endDateNext"), taskSub.getWeek());
                            taskUnit.setTimeLimit(dates[0]);
                            taskMain.setTimeLimit(dates[0]);
                        }
                    } else if ("2".equals(taskSub.getPeriod())) {
                        String yearStr = year + "";
                        String monthStr = month + "";
                        String dayStr = day + "";
                        if (month < 10) {
                            monthStr = 0 + monthStr;
                        }
                        if (day < 10) {
                            dayStr = 0 + dayStr;
                        }
                        //判断当前日期与周期的日期大小
                        if (day < Integer.parseInt(taskSub.getMonth())) {
                            //如果小于。时限为本月日期
                            String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                            taskUnit.setTimeLimit(time);
                            taskMain.setTimeLimit(time);
                        } else {
                            //不小于就是下月日期
                            if (month == 12) {
                                year = year + 1;
                                String time = year + "-01-" + taskSub.getMonth();
                                taskUnit.setTimeLimit(time);
                            } else {
                                month = month + 1;
                                if (month < 10) {
                                    monthStr = "0" + month;
                                }
                                String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                taskUnit.setTimeLimit(time);
                                taskMain.setTimeLimit(time);
                            }
                        }
                    } else {
                        //每季度
                        //第一个反馈时限
                        taskUnit.setTimeLimit(taskSub.getQuarter());
                        taskMain.setTimeLimit(taskSub.getQuarter());
                    }
                } else {
                    //多时限
                    taskUnit.setTimeType("3");
                    taskUnit.setTimeLimits(taskSub.getTimeLimits());
                    //取出当前多时限的的第一个时限
                    if (taskSub.getTimeLimits().contains(",")) {
                        String[] split = taskSub.getTimeLimits().split(",");
                        taskUnit.setTimeLimit(split[0]);
                        taskMain.setTimeLimit(split[0]);
                    } else {
                        //只选择了一个
                        taskUnit.setTimeLimit(taskSub.getTimeLimits());
                        taskMain.setTimeLimit(taskSub.getTimeLimits());
                    }
                }*/
                taskUnit.setDeptName(dept.getDeptName());
                //设置为待办
                taskUnit.setState("0");
                //第一轮
                taskUnit.setTimeRound("1");
                taskUnitService.save(taskUnit, user.getSysId());
                //记录任务流程
                //发送短信。查询当前单位的领导
                SysUserFilter userFilter = new SysUserFilter();
                userFilter.setRoleId("02");
                userFilter.setDeptId(dept.getSysId());
                List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                for (SysLogin sysLogin : loginList) {
                    SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                    String mobile = sysUser.getMobile();
                    if (StringUtils.isNotBlank(mobile)) {
                        // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                        HashMap<String, String> map = new HashMap<>();
                        map.put("userName", sysUser.getName());
                        map.put("tel", sysUser.getMobile());
                        map.put("taskName", taskUnit.getTaskMainName());
                        smsMap.put(sysLogin.getSysId(), map);
                    }
                }
                TaskLogNew taskLogNew = new TaskLogNew();
                taskLogNew.setTaskUnitId(taskUnit.getSysId());
                String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + dept.getDeptName() + "牵头";
                taskLogNew.setContent(s);
                taskLogNewService.save(taskLogNew, user.getSysId());
            }
            this.update(taskMain);
        }
        //取出协办单位
        String assistDeptIds = filter.getAssistDeptIds();
        if (StringUtils.isNotBlank(assistDeptIds)) {
            String[] strings = assistDeptIds.split(",");
            for (String assistDeptId : strings) {
                SysDept dept = sysDeptService.getById(assistDeptId);

                TaskUnit taskUnit = new TaskUnit();
                taskUnit.setDeptId(assistDeptId);
                taskUnit.setUnitType("2");//xieban单位
                taskUnit.setTaskSubId(taskSub.getSysId());
                taskUnit.setType("0");
                taskUnit.setTaskMainId(taskMain.getSysId());
                taskUnit.setTaskSubName(taskSub.getSubName());
                taskUnit.setCategoryId(taskMain.getCategoryId());
                taskUnit.setTaskMainName(taskMain.getMainName());
                taskUnit.setDeptName(dept.getDeptName());
                taskUnit.setStatus(taskSub.getStatus());

                taskUnit.setTimeType(taskSub.getTimeType());
                taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                taskUnit.setTimeLimits(taskSub.getTimeLimits());
                taskUnit.setPeriod(taskSub.getPeriod());
                taskUnit.setDay(taskSub.getDay());
                taskUnit.setWeek(taskSub.getWeek());
                taskUnit.setMonth(taskSub.getMonth());
                taskUnit.setQuarter(taskSub.getQuarter());
                taskUnit.setImp(taskSub.getImp());

               /* if ("1".equals(taskSub.getTimeType())) {
                    taskUnit.setTimeType("1");
                    //判断协办单位是否有单独时限
                    if (StringUtils.isNotBlank(taskMain.getLessDays())) {
                        String format = xiebanLimit(taskSub.getSubTimeLimit(), taskMain.getLessDays());
                        taskUnit.setTimeLimit(format);
                    } else {
                        taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                    }
                } else if ("2".equals(taskSub.getTimeType())) {
                    //周期性
                    taskUnit.setTimeType("2");
                    taskUnit.setPeriod(taskSub.getPeriod());
                    taskUnit.setWeek(taskSub.getWeek());
                    taskUnit.setMonth(taskSub.getMonth());
                    if ("0".equals(taskSub.getPeriod())) {
                        //如果是按天的周期性反馈。
                        int dayInt = Integer.parseInt(taskSub.getDay());
                        long millis = System.currentTimeMillis();//当前时间的毫秒值
                        long timeLimitIong = millis + dayInt * 3600 * 24 * 1000;
                        String timeLimitDay = simdate1.format(timeLimitIong);//当前任务时限
                        taskUnit.setTimeLimit(timeLimitDay);
                        taskMain.setTimeLimit(timeLimitDay);
                    } else if ("1".equals(taskSub.getPeriod())) {
                        //如果是每周获取当前日期是周几
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(new Date());
                        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                        if (w < 0) {
                            w = 7;
                        }
                        //判断周期性与当前星期的大小
                        if (w < Integer.parseInt(taskSub.getWeek())) {
                            //如果小于，时限为本周周几
                            Map<String, String> weekDate = WeekDayUtil.getWeekDate();
                            String[] dates = WeekDayUtil.getDates(weekDate.get("mondayDate"), weekDate.get("sundayDate"), taskSub.getWeek());
                            //协办提前天
                            if (StringUtils.isBlank(taskMain.getLessDays())) {
                                taskUnit.setTimeLimit(dates[0]);
                            } else {
                                taskUnit.setTimeLimit(xiebanLimit(dates[0], taskMain.getLessDays()));
                            }
                        } else {
                            //如果相同。时限为下周周几
                            Date now = new Date();
                            Map<String, String> nextWeek = WeekDayUtil.getNextWeek(simdate1.format(now));
                            String[] dates = WeekDayUtil.getDates(nextWeek.get("beginDateNext"), nextWeek.get("endDateNext"), taskSub.getWeek());
                            //协办提前天
                            if (StringUtils.isBlank(taskMain.getLessDays())) {
                                taskUnit.setTimeLimit(dates[0]);
                            } else {
                                taskUnit.setTimeLimit(xiebanLimit(dates[0], taskMain.getLessDays()));
                            }
                        }
                    } else if ("2".equals(taskSub.getPeriod())) {
                        String yearStr = year + "";
                        String monthStr = month + "";
                        String dayStr = day + "";
                        if (month < 10) {
                            monthStr = 0 + monthStr;
                        }
                        if (day < 10) {
                            dayStr = 0 + dayStr;
                        }
                        //判断当前日期与周期的日期大小
                        if (day < Integer.parseInt(taskSub.getMonth())) {
                            //如果小于。时限为本月日期
                            String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                            //协办提前天
                            if (StringUtils.isBlank(taskMain.getLessDays())) {
                                taskUnit.setTimeLimit(time);
                            } else {
                                taskUnit.setTimeLimit(xiebanLimit(time, taskMain.getLessDays()));
                            }
                        } else {
                            //不小于就是下月日期
                            //不小于就是下月日期
                            if (month == 12) {
                                year = year + 1;
                                String time = year + "-01-" + taskSub.getMonth();
                                if (StringUtils.isBlank(taskMain.getLessDays())) {
                                    taskUnit.setTimeLimit(time);
                                } else {
                                    taskUnit.setTimeLimit(xiebanLimit(time, taskMain.getLessDays()));
                                }
                            } else {
                                month = month + 1;
                                if (month < 10) {
                                    monthStr = "0" + month;
                                }
                                String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                if (StringUtils.isBlank(taskMain.getLessDays())) {
                                    taskUnit.setTimeLimit(time);
                                } else {
                                    taskUnit.setTimeLimit(xiebanLimit(time, taskMain.getLessDays()));
                                }
                            }
                        }
                    } else {
                        //季度
                        //每季度
                        //第一个反馈时限
                        taskUnit.setTimeLimit(xiebanLimit(taskSub.getQuarter(), taskMain.getLessDays()));
                    }
                } else {
                    //多时限
                    taskUnit.setTimeType("3");
                    taskUnit.setTimeLimits(taskSub.getTimeLimits());
                    //取出当前多时限的的第一个时限
                    if (taskSub.getTimeLimits().contains(",")) {
                        String[] split = taskSub.getTimeLimits().split(",");
                        if (StringUtils.isBlank(taskMain.getLessDays())) {
                            taskUnit.setTimeLimit(split[0]);
                        } else {
                            taskUnit.setTimeLimit(xiebanLimit(split[0], taskMain.getLessDays()));
                        }
                    } else {
                        //只选择了一个
                        String format = xiebanLimit(taskSub.getSubTimeLimit(), taskMain.getLessDays());
                        taskUnit.setTimeLimit(format);
                    }
                }*/
                taskUnit.setDeptName(dept.getDeptName());
                //设置为待办
                taskUnit.setState("0");
                //第一轮
                taskUnit.setTimeRound("1");
                taskUnitService.save(taskUnit, user.getSysId());
                       /* TimeLimit timeLimit = new TimeLimit();
                        timeLimit.setTaskUnitId(taskUnit.getSysId());
                        timeLimit.setTimeType(taskSub.getTimeType());
                        timeLimit.setPeriod(taskSub.getPeriod());
                        timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                        timeLimit.setTimeLimits(taskSub.getTimeLimits());
                        timeLimit.setState("1");
                        timeLimitService.save(timeLimit);*/
                //记录任务流程
                //发送短信。查询当前单位的领导
                SysUserFilter userFilter = new SysUserFilter();
                userFilter.setRoleId("02");
                userFilter.setDeptId(dept.getSysId());
                List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                for (SysLogin sysLogin : loginList) {
                    SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                    String mobile = sysUser.getMobile();
                    if (StringUtils.isNotBlank(mobile)) {
                        // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                        HashMap<String, String> map = new HashMap<>();
                        map.put("userName", sysUser.getName());
                        map.put("tel", sysUser.getMobile());
                        map.put("taskName", taskUnit.getTaskMainName());
                        smsMap.put(sysLogin.getSysId(), map);
                    }
                }

                TaskLogNew taskLogNew = new TaskLogNew();
                taskLogNew.setTaskUnitId(taskUnit.getSysId());
                String s = user.getName() + "立项： " + taskSub.getSubName() + ",由" + dept.getDeptName() + "协办";
                taskLogNew.setContent(s);
                taskLogNewService.save(taskLogNew, user.getSysId());
            }
        }
        int t0 = taskUnitService.getCountByType(taskMain.getSysId(), "0");
        int t1 = taskUnitService.getCountByType(taskMain.getSysId(), "1");
        int t2 = taskUnitService.getCountByType(taskMain.getSysId(), "2");
        int t3 = taskUnitService.getCountByType(taskMain.getSysId(), "3");
        int t4 = taskUnitService.getCountByType(taskMain.getSysId(), "4");
        int t5 = taskUnitService.getCountByType(taskMain.getSysId(), "5");
        int o = taskUnitService.getCountByStatus(taskMain.getSysId(), "1");
        taskMain.setTypeExplain("待签收: " + t0 + "；已签收：" + t5 + " ；待反馈: " + t1 + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);

        taskMain.setOverdueExplain("逾期单位任务: " + o);
        this.update(taskMain);

        //发送短信
        for (Map.Entry<String, HashMap<String, String>> entry : smsMap.entrySet()) {
            HashMap<String, String> obj = entry.getValue();
            String taskName = obj.get("taskName");
            String tel = obj.get("tel");
            String userName = obj.get("userName");
            smsUtilService.taskNewSmsService(taskName, tel, userName);
        }

        return "200";
    }

    /**
     *
     * 存放发送短信的领导
     * @param deptId
     * @param taskMainName
     * @param smsMap
     */
    private void  setSmsLeader(String deptId,String taskMainName,HashMap<String,HashMap<String,String>> smsMap){
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("02");//公共账号
        userFilter.setDeptId(deptId);
        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        for (SysLogin sysLogin : loginList) {

            SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
            String mobile = sysUser.getMobile();
            if (StringUtils.isNotBlank(mobile)) {
                // smsUtilService.taskNewSmsService(taskUnit, sysUser);
                HashMap<String, String> map = new HashMap<>();
                map.put("userName", sysUser.getName());
                map.put("tel", sysUser.getMobile());
                map.put("taskName", taskMainName);
                smsMap.put(sysLogin.getSysId(), map);
            }


        }

    }



    /**
     * 保存攻坚任务
     */
    public  void saveGongJianTask(TaskMainFilter filter)
    {

        HashMap<String, HashMap<String, String>> smsMap = new HashMap<>();//发短信专用

        List<TaskSubFilter> taskSubs = filter.getTaskSubFilterList();//导入的所有子任务
        //按照督查组分组
        Map<String, List<TaskSubFilter>> mainTaskMap = taskSubs.stream().collect(Collectors.groupingBy(TaskSubFilter::getInspectionId));

        //获取统一的编码
        String gongJianTaskId = tableService.updateMaxSysId("t_task_main", null);

//        this.beforeSave(new TaskMain());
        for (Map.Entry<String ,List<TaskSubFilter>> entry:mainTaskMap.entrySet() ){
            TaskMain  taskMain = new TaskMain();

            BeanUtils.copyProperties(filter,taskMain,"inspectionId");

            taskMain.setStatus("2");
            taskMain.setImp(2);
            taskMain.setGjId(gongJianTaskId);
            taskMain.setInspectionId(entry.getKey());
            taskMain.setCategoryId("gongjianTask");
            taskMain.setCrucialUser(SysUserUtils.getUserId());

            this.save(taskMain);

            String planEndDate = filter.getPlanEndDate();
            if(StringUtils.isNotBlank(planEndDate))
            {
                TaskEndDate endEntity = new TaskEndDate();
                endEntity.setTaskMainId(taskMain.getSysId());
                endEntity.setEndDate(planEndDate);
                endDateService.save(endEntity);
            }


            //特殊任务表
            SpecialTask spTask = new SpecialTask();
            spTask.setTaskMainId(taskMain.getSysId());
            spTask.setTaskMainName(taskMain.getMainName());
            spTask.setInspectionId(taskMain.getInspectionId());
            spTask.setType(0+""); //0 代签收
            spTask.setTimeRound(1+"");

            spTask.setStatus(1+"");
            spTask.setTaskType(1+""); // 1= 攻坚  2 =重大事项

            spTask.setTimeType(filter.getTimeType2());
            spTask.setTimeLimit(filter.getTimeLimit2());
            spTask.setTimeLimits(filter.getTimeLimits2());
            spTask.setPeriod(filter.getPeriod2());
            spTask.setDay(filter.getDay2());
            spTask.setWeek(filter.getWeek2());
            spTask.setMonth(filter.getMonth2());
            spTask.setQuarter(filter.getQuarter2());


            specialTaskService.save(spTask);

            //处理子任务
            List<TaskSubFilter> subTaskLists = entry.getValue();

            String[] leadDeptArray = {};
            String[] assDeptArray = {};
            for (TaskSubFilter subItem : subTaskLists) {
                //处理子任务
                TaskSub taskSub = new TaskSub();
                taskSub.setStatus(taskMain.getStatus());//子任务状态与主任务相同
                taskSub.setTaskMainId(taskMain.getSysId());
                taskSub.setSubName(StringUtils.isBlank(subItem.getSubName())?taskMain.getMainName():subItem.getSubName());//设置事项名称
                TaskMainFilter temFilter  = new TaskMainFilter();
                BeanUtils.copyProperties(taskMain,temFilter);
                setTaskSubTime(subItem,taskSub,temFilter);
                taskSub.setImp(taskMain.getImp());
                taskSubService.save(taskSub);


                //定时任务扫表表
                TimeLimit timeLimit = new TimeLimit();
                timeLimit.setTaskSubId(taskSub.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(taskSub.getTimeType());
                timeLimit.setPeriod(taskSub.getPeriod());
                timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                timeLimit.setTimeLimits(taskSub.getTimeLimits());
                timeLimit.setDay(taskSub.getDay());
                timeLimit.setWeek(taskSub.getWeek());
                timeLimit.setMonth(taskSub.getMonth());
                timeLimit.setQuarter(taskSub.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit);

                //处理单位任务
                String leadDeptIds = subItem.getLeadDeptIds();
                    //牵头单位
                leadDeptArray = leadDeptIds.split(",");
                for (String leadDept:leadDeptArray) {
                    TaskUnit taskUnit = new TaskUnit();
                    taskUnit.setDeptId(leadDept);
                    taskUnit.setUnitType("1");//牵头单位
                    taskUnit.setTaskMainName(taskMain.getMainName());
                    taskUnit.setTaskSubId(taskSub.getSysId());
                    taskUnit.setType("0");
                    taskUnit.setTaskMainId(taskMain.getSysId());
                    taskUnit.setTaskSubName(taskSub.getSubName());
                   // taskUnit.setCategoryId(taskMain.getCategoryId());//事项类型
                    taskUnit.setStatus(taskSub.getStatus());
                    taskUnit.setImp(taskSub.getImp());
                    setTaskUnitTime(taskUnit,taskSub);
                    taskMain.setTimeLimit(taskUnit.getTimeLimit());
                    String deptStr = redisService.get("dept:" + leadDept);
                    SysDept sysDept = JSONObject.parseObject(deptStr, SysDept.class);
                    if(ObjectUtils.isNotBlank(sysDept))
                    {
                        taskUnit.setDeptName(sysDept.getDeptName());

                    }

                    //设置为待办
                    taskUnit.setState("0");
                    //第一轮
                    taskUnit.setTimeRound("1");

                    taskUnitService.save(taskUnit);

                    setSmsLeader(taskUnit.getDeptId(),taskMain.getMainName(),smsMap);

                }
                    //协办单位
                String assistDeptIds = subItem.getAssistDeptIds();
                if(StringUtils.isNotBlank(assistDeptIds)){  // 不为空的情况下

                    assDeptArray = assistDeptIds.split(",");
                    for (String assDept : assDeptArray) {
                        TaskUnit taskUnit = new TaskUnit();
                        taskUnit.setDeptId(assDept);
                        taskUnit.setUnitType("2");//xieban单位
                        taskUnit.setTaskSubId(taskSub.getSysId());
                        taskUnit.setType("0");
                        taskUnit.setTaskMainId(taskMain.getSysId());
                        taskUnit.setTaskSubName(taskSub.getSubName());
                        taskUnit.setCategoryId(taskMain.getCategoryId());
                        taskUnit.setTaskMainName(taskMain.getMainName());
                        taskUnit.setStatus(taskSub.getStatus());

                        setTaskUnitTime(taskUnit,taskSub);
                        taskMain.setTimeLimit(taskUnit.getTimeLimit());
                        String deptStr = redisService.get("dept:" + assDept);
                        SysDept sysDept = JSONObject.parseObject(deptStr, SysDept.class);
                        if(ObjectUtils.isNotBlank(sysDept))
                        {
                            taskUnit.setDeptName(sysDept.getDeptName());

                        }
                        // taskUnit.setDeptName(dept.getDeptName());
                        //设置为待办
                        taskUnit.setState("0");
                        //第一轮
                        taskUnit.setTimeRound("1");
                        taskUnit.setImp(taskSub.getImp());
                        taskUnitService.save(taskUnit);

                        setSmsLeader(taskUnit.getDeptId(),taskMain.getMainName(),smsMap);

                    }
                }


            }
            int i =assDeptArray.length+ leadDeptArray.length;
            taskMain.setTypeExplain("待签收: " + i + "; 待反馈: " + 0 + "; 已反馈: " + 0 + "; 重办: " + 0 + "; 完成: " + 0);
            taskMain.setOverdueExplain("逾期单位任务: " + 0);
            this.update(taskMain);






        }

//保存范围








        //发送短信通知主要领导和公共账号吧
        for (Map.Entry<String, HashMap<String, String>> entry : smsMap.entrySet()) {
            HashMap<String, String> obj = entry.getValue();
            String taskName = obj.get("taskName");
            String tel = obj.get("tel");
            String userName = obj.get("userName");
            smsUtilService.taskNewSmsService(taskName, tel, userName);
        }




    }

    /**
     * 主任务 -获取攻坚任务
     * 合并攻坚任务
     * @return
     */
    public List<TaskMainFilter> getGongJianTasks(TaskMainFilter filter)
    {
        List<TaskMain> gjTask = taskMainDao.getGjTask(filter);
        List<TaskMainFilter>  listData =new ArrayList<>();
        for (TaskMain taskMain : gjTask) {
            String gjId = taskMain.getGjId();
            TaskMainFilter mainfilter = new TaskMainFilter();
            mainfilter.setGjId(gjId);
            List<TaskMain> taskMains = taskMainDao.queryFilter(mainfilter);
            TaskMainFilter data = new TaskMainFilter();

            BeanUtils.copyProperties(taskMain,data);
            String duchaName="";
            for (TaskMain main : taskMains) {
                String inspectionId = main.getInspectionId();
                String strdept = redisService.get("dept:" + inspectionId);
                SysDept sysDept = JSONObject.parseObject(strdept, SysDept.class);
               // data.setDeptName(sysDept.getDeptName());
                duchaName=duchaName+sysDept.getDeptName()+"、";
            }
            if(StringUtils.isNotBlank(duchaName))
            {

                duchaName=duchaName.substring(0,duchaName.length()-1);
            }
            data.setInspectionName(duchaName);
            listData.add(data);

        }

        return listData;

    }


    @Transactional
    public  void updateStopAllTask(String taskMainId)
    {
        //取出所有子任务
        List<TaskSub> subTasks = taskSubService.getByMainId(taskMainId);

        //调度时间表
        for (TaskSub subTask : subTasks) {

            List<TimeLimit> limits = timeLimitService.getBySubId(subTask.getSysId());
            if(ObjectUtils.isNotBlank(limits))
            {
                for (TimeLimit limit : limits) {
                    timeLimitService.delete(limit);
                }
            }
//            cycle 0 需要循环，1 不要循环  0未终止，1 已经终止
            List<TaskUnit> taskUnits = taskUnitService.getBySubId2(subTask.getSysId());
            taskUnits.forEach(taskUnit ->taskUnit.setCycflag(1) );

            taskUnitService.batchUpdate(taskUnits);

        }




    }





}
